Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel Authorization for Eloquent collection

Tags:

laravel-5.1

How to apply laravel Gate (http://laravel.com/docs/5.1/authorization) for an eloquent collection.

It works for single item like below

$post = Post::findOrFail($id);

if ($user->cannot('view-post', $post)) {
   abort(403);
}

But not working for a collection. Is it possible to filter the collection using Gate and return a collection?

$posts = Post::all();
like image 970
Saravanan Avatar asked Sep 29 '15 17:09

Saravanan


1 Answers

I have the same question. Maybe some like this:

$post->filter(function($value,$key){
  if(\Gate::allows('view-post',$value)){
    return $val;
  }
});

but there must be a better solution.

Related links:
https://laravel.com/docs/5.2/collections#method-filter
https://laravel.com/docs/5.2/authorization

like image 133
Nicolas Fall Avatar answered Oct 04 '22 18:10

Nicolas Fall