Laravel 5.2 route model binding

Laravel has a documentation regarding route model binding which could be found here. But there is no example with regards to this kind of scenario:

Route::get('search/', '<a href="https://getridbug.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="6120131508020d04220e0f15130e0d0d041321120400130209">[email protected]</a>');

How to I implicitly bind a model into the route? I know I could do something like this directly on the controller’s method.
public function search(Model $model) {
    // some code here
}

But I’m just curious on how to do it on the routes instead.

I am after this approach

Route::get('search/{article}', function(ArticlesModel $articlesModel) {
    // this should be calling '<a href="https://getridbug.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="9edfeceaf7fdf2fbddf1f0eaecf1f2f2fbecdeedfbffecfdf6">[email protected]</a>'
});

Thanks!

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

Because your variable is called $model, Laravel will look for a wildcard segment of the url written as {model}:

In routes.php:

Route::get('search/{article}', '<a href="https://getridbug.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="1051626479737c75537f7e64627f7c7c756250637571627378">[email protected]</a>');

In controller:
function search(Article $article) {
    //$article is the Article with the id from {article}, ie. articles/2 is article 2
}

Edit… the way that you are suggesting doesn’t really make sense. That would just be an extra step that is skipped entirely by just using "[email protected]". I think this code would function although I don’t recommend it:
Route::get('search/{article}', function(Article $article)
{
    $controller = App::make(ArticleController::class);
    return App::call([$controller, 'search'], compact('article'));
}

Method 2

routes.php

Route::get('search/{article}', '<a href="https://getridbug.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="7130030518121d14321e1f05031e1d1d140331021410031219">[email protected]</a>');

ArticleController.php
public function search(Model $article) {
    // some code here
}


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x