3

I am new to laravel and voyager

I have one question about voyager. The thing is .. I want to let user do CRUD only on the records created by him/her, so records of other users won't be accessible to him/her but can do add-edit-delete ONLY on his records. How can I archive this in voyager ? The default permissions are working on all records, those does not filter user specific records :(

Darek P
  • 61
  • 5
  • I've never used Voyager, but the basic idea would be to have a `created_by` (or equivalent, such as `creator`, `user_id`, `owner_id`, etc etc) on each Table/Model and filter via relationships (`Model::where("created_by", "=", $user->id)->get()` or `$user->model->get();`) This question is a little to broad as it stands. Try to implement something, and if you have a specific issue, post another question. – Tim Lewis May 22 '18 at 18:19

1 Answers1

1

Landlord should work perfectly for this.

Landlord will apply a global scope to Eloquent that filters records automatically. It does this at a level lower than Voyager in the stack, meaning you won't need any extra configuration on the Voyager end of things.

With Landlord you simply add a column to all your CRUD tables that identify ownership of a record, and then you let Landlord know about this.

For example if you go with the column name user_id, you can then scope to the user anywhere (say in your middleware) with a call as simplistic as Landlord::addTenant('user_id', $userIdHere); Here's an example middleware:

<?php
namespace App\Http\Middleware;
use Closure;
use App\User;
use Landlord as LandlordManager;

class Landlord {
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if ($request->user()) {
            LandlordManager::addTenant($request->user());
            LandlordManager::applyTenantScopesToDeferredModels();
        }
    }
}

You then go to App/Http/Kernel.php, find the $routeMiddleware array and add:

'landlord' => \App\Http\Middleware\Landlord::class

Then go to app/routes/web.php and apply this middleware to any single route or route group according to your favourite flavour in the docs https://laravel.com/docs/master/middleware. An example being:

Route::group(['prefix' => 'admin', 'middleware'=>'landlord'], function () {
    // routes here
});
Sam
  • 2,276
  • 1
  • 19
  • 23