Question: Laravel implicit model binding omit parameter


Laravel implicit model binding omit parameter

Answers 1
Added at 2017-01-05 20:01

I'm using implicit model binding in Laravel 5.3.26 for routes like this

POST /teams/{team}/customers/{customer}/addresses

The {team} is used in a middleware to determine which team the user is currently using. However the store method for the addresses only needs the {customer} injected; it does not access the team in any way. So the header of the method could look like this:

public function store(Customer $customer, Request $request)

Unfortunately the id of the selected team gets injected into $customer instead of the actual Customer instance. If I add the $team parameter to the store method, so the function header would look like this:

public function store(Team $team, Customer $customer, Request $request)

everything works as expected. Is there a way to omit the $team parameter but still get the correct Customer instance injected into the function ?

Answers to

Laravel implicit model binding omit parameter

nr: #1 dodano: 2017-01-05 21:01

I think you should just make a different route for this:

Route::put('customers', 'CustomerController@store')-name('');

Then your form:

<form action="{{ route('') }}' method="POST">
    {{ method_field('PUT') }}
    {{ csrf_field() }}
    //other stuff

Alternatively, if you must, you can just use a ? in the route to dictate that the model may or may not be present:

Route::post('/teams/{team?}/customers/{customer}/addresses', 'Controller@method');

Then in your controller method, you'd still have to define $team, but it may or may not exist, such as:

public function store(Request $request, $team = null, Customer $customer)

Side Note Request should always come first.

Source Show
◀ Wstecz