Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

gdanielrg's avatar

Implicit model binding, custom resolve for some methods

Im trying to leverage from the Implicit route model binding of laravel 5.2. I have a page that shows an article with its comments etc.

my routes are as follow:

Route::singularResourceParameters();
Route::group(['middleware' => 'web'], function () {
    Route::group(['prefix' => 'blog', 'namespace' => 'Guest'], function()
    {
        Route::bind('article', function ($value) {
            return App\Models\Article::with('user')->with('channel')->with('comments')->find($value);
        });
        Route::resource('articles', 'ArticlesController');
    });
});

and in my controller I have this:

class ArticlesController extends Controller
{
    public function show(Article $article)
    {   
        return view('guest.articles.show', ['article' => $article]);
    }

    public function getEdit(Article $article)
    {   
        return view('guest.articles.edit', ['article' => $article]);
    }
}

The problem is that as you can see i specified a custom way I want the article to be resolved before passing it to the controller, because I needed the comments, channel, and user relationships eager loaded just for the show() method since that displays the article with all that information, but when I want to edit the article or any other method, I don't need all those eager loaded relationships, how can I specify that I want that custom resolve only for the show() method?

0 likes
6 replies
d3xt3r's avatar

because I needed the comments, channel, and user relationships eager loaded just for the show()

Eager loading is done to handle N+1 problem, if you wan't the relation just for your show method, defer it to the show method, use Lazy Eager Loading using $article()->load(['relations']);

gdanielrg's avatar

But there are some other cases where I will want that as well, Basically I just want to learn how to do it even though it may not be the best solution for this case in particular

d3xt3r's avatar

I don't think its possible to bind same key to different behaviours.

gdanielrg's avatar

So how then I should be different keys? like instead of article use detailedArticle and then bind that to an eager loaded model?

d3xt3r's avatar
d3xt3r
Best Answer
Level 29

You could do that ... but why, you could simply write a function in controller for lazy loading, after all its in controller that you will require it ??

gdanielrg's avatar

Ok Ill do that seems like the smartest thing to do.

Please or to participate in this conversation.