mardi 26 septembre 2017

How can I redirect a Laravel route without a parameter to a controller method with a default parameter?

Assume the following routes in a Laravel 5.5 API:

// custom routes for THIS user (the user making the request)
Route::get('/user', 'UserController@show');
Route::get('/user/edit', 'UserController@edit');

// register CRUDdy resource routes for users
Route::resource('users', 'UserController');

Let's use edit as the example:

public function edit(User $user)
{
    ...
}

As you can see, the edit route contains a type-hinted $user parameter. This works just fine for the users/13/edit route, as expected. However, I'd to configure the route /user/edit to pass along the $request->user() user object to the function. I don't want to check for the user object in the actual edit method as that could interfere with other validation (for instance, I don't want to default to the current user if someone passes a non-existent user ID, I want to return an error in that case).

In short: how can I register a route to first create a parameter, then pass it to the given controller method? My first thought was to use a closure:

Route::get('/user/edit', function(Request $request){
    $user = $request->user();
});

But once inside the closure, I'm not certain how to then carry the request forward to the appropriate controller method.



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2fxlcPL
via IFTTT

Aucun commentaire:

Enregistrer un commentaire