'how to get name from url dynamically

How to get a part of the url?

query to be made:

$name = 'LeSant'; // (from url dinamic) //
$event = Dias::where('name', $name)->first();

enter image description here

How can I get name from the url? /event/LeSant



Solution 1:[1]

It depends on how you are declared this route. You can specify model parameter and with laravel route binding you can inject model in your controller method https://laravel.com/docs/9.x/routing#customizing-the-key

In routes/web.php:

Route::get('/events/{event:name}', [EventController::class, 'show']);

And in EventController controller you can use something like that:

public function show(Event $event)
{
    // do something with $event
}

Or if it not suits to you can get last element from request()->segments()

Solution 2:[2]

Multiple ways to do that. You can use request helper for it. Below two ways with requesthelper:

  1. request()->segment(count(request()->segments()))
  2. last(request()->segments())

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Mykola Bokoch
Solution 2 Maik Lowrey