Skip to content
Advertisement

Block a resource for only one user in laravel PHP AJAX and redirect the other to a readonly form

I create an application with laravel 5.5. I use so PHP AJAX and MySQL.

I have a problem. An user connect with his account on the application and when he will click on an element (for example a contact card), I want to redirect this user on a form in readonly because another user is in current card. This another user see the form to edit the card.

In fact, I want to block a resource for only one user in edit. The other users will be in readonly (redirect to another route)

Is it possible to use a middleware? Use the cookies? Or launch an Ajax route when the user close his browser or tab page?

Help me….

Advertisement

Answer

Add new nullable field to the database on your resource to keep current user id that responsible for the edit. Then add a middlware which will check if this field is null then free to edit, if not be readonly.

for example you have a products table:

id title group_id editor_id


1 bicycle 1 5
2 car 3 null

Resource id 1 only be editable by user id 5.
Resource id 2 is editable any user who start editing.

and then after the user exit or any other behavior you like, try to make it null again to be editable by others.

middlware code:

// find the resource
$resource = Resource::find($request->resource_id);

// current user is last user. so no need to check.
if($resource->editor_id == auth()->user()->id) return $next($request);

// check if 10 minutes passed from last edit by another user.
if(Carbon::now()->diffInMinutes(Carbon::parse($resource->updated_at)) >= 10) {
    // replace current user id with last one.
    $resource->editor_id = auth()->user()->id;
    $resource->save();
} else {
    return response('You dont have permission to edit.');
}
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement