I'm creating a Laravel web site where users can login and upload images. For visitors to see that user's gallery, I've set up a gallery page with a URL like https://localhost8000/gallery/2, where 2 is the user ID.
My current code looks like this.
web.php
Route::get('/menu/{user}', 'CartController@menu');
CartController.php
public function menu($user)
{
$user = User::findOrFail($user);
return view('new_menu')->with(['user' => $user]);
}
Instead of using the user ID as a route parameter, I want to use a random string. Currently a random string of 32 digits is created when the user registers and stored in the users
table in a column called random
.
I couldn't figure out how to relate "random" to "user" in web.php and Controller.
When using route model binding (which you should always be doing) Laravel handles the lookup for you. This behaviour is triggered by including the parameter type in the method signature:
public function menu(User $user)
{
return view('new_menu')->with(['user' => $user]);
}
No lookups needed, and Laravel will automatically handle 404s for you. (Note the name of the route parameter must also match the name of the variable in the method signature.)
You can also specify the key used to lookup the model instance, instead of the default of using the model's primary key:
Route::get('/menu/{user:random}', 'CartController@menu');
This presumes that the random
column has a UNIQUE
index, otherwise results may be unpredictable.