Erhnam
Erhnam

Reputation: 921

Laravel 5.2 Route Model Binding using methods and controller

I have configured my route the following way:

Route::model('terms', 'Term');
Route::resource('terms', 'TermController');
Route::bind('terms', function($value, $route) {
    return App\Term::whereId($value)->first();
});

This results in having automatically the term model available with default methods: edit, show, etc...

See below a code snippet from my controller:

public function update(Term $term) {
 //update term
}

However I want to extend my controller with a couple of new methods. So when I navigate to terms/{term}/review the $term is automatically injected into my controller. Is there any way to do this? Some like below?

Route::get('terms/{term}/review', function (App\Term $term) {
   use TermController@review;
});

Upvotes: 0

Views: 264

Answers (1)

baikho
baikho

Reputation: 5358

You defined the route module binding with Route::bind for the terms URI segment, so there's no need to specify that again in the additional route. As for the additional route, it should best be defined before the Route::resource (see supplementing a resource controller).

You can write out your routes like this:

// Additional resource routes should be called before Resource::resource
Route::get('terms/{terms}/review', 'TermController@showReview');

// Init resource controller
Route::resource('terms', 'TermController');

// URI binding resolution for 'terms'
Route::bind('terms', function($value) {
    return App\Term::whereId($value)->first();
});

And then add the additional method to your resource controller:

public function showReview(\App\Term $term)
{
    dd($term); // $term is an instance of your App\Term.
}

Upvotes: 1

Related Questions