Support the ongoing development of Laravel.io →
Requests Eloquent
Last updated 2 years ago.
0

I would recommend going a step deeper, and creating Route Model Binding:

So in your app/Providers/RouteServiceProvider.php:

/**
 * Define your route model bindings, pattern filters, etc.
 *
 * @return void
 */
public function boot(Router $router)
{
    $router->bind(
        'posts',
        function ($routeArgument) {
            if(\Auth::user()->cannot('see_all')) {
                return \Auth::user()->posts()->findOrFail($routeArgument);
            }
        
            return Post::findOrFail($routeArgument);
        }
    );

    parent::boot($router);
}

Remember to import your Post model. :)

This gains to two things:

  1. You won't have to grab your model manually in every single method
  2. You can extract your, quite simple, logic out of your controller

Read more about Route Model Binding here.

0

This is a good solution but I still have a problem...

On my PostsController :

public function index() {

if(Auth::user()->cannot('see_all'))
    $post= Auth::user()->posts;
else
    $post= Post::all();

}

This cannot be replaced by your solution :/ That's why I think it's better to use scope, no?

Last updated 8 years ago.
0

Sign in to participate in this thread!

Eventy

Your banner here too?

LonnyX lonnyx Joined 30 Mar 2015

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2024 Laravel.io - All rights reserved.