Last updated on February 28, 2023
In this article, we will learn to get URL segments in controller and blade using the Laravel framework. We have the below route in the web.php
that is located in the routes directory.
Route::get('/user/{id}', [UserController::class, 'edit']);
This route creates the following URL,
http://127.0.0.1:8000/user/1
In this URL 1 is the id of the user, which can be helpful for many tasks for example edit, delete, etc. This id is the 2nd or last segment of the URL.
We have a user controller and blade file along with the route. In the controller edit method simply returns a view of the blade file that is edit-user.blade.php
.
Laravel allows getting URL segments in the controller. Laravel’s Request class has a segments()
method that gets URL segments. It returns segments in array format and the first index starts from 0. Let’s pass the Request class instance into the edit method to access the segments()
method.
public function edit(Request $request)
{
return view('edit-user');
}
Now in edit()
method, we can access segment()
method
$segments = $request->segments();
Request’s class method segments()
has the ability to get all segments and convert them into an array. In the above-mentioned URL, there are two segments. So we have ‘user’ and 0 index and 1 id at 1 index. Following is the code and result,
$segments[0]; /* output: user */
$segments[1]; /* output: 1 */
In Laravel, we can directly use a few classes in the blade file, Request class is one of them. As we know that URL segments can be accessible through Request’s class method segments()
. So open PHP tags and add the following code in the edit-user.blade.php file,
@php
$segments = Request::segments();
@endphp
Now, we have both segments that are stored in the $segments
variable in the array. We can print the segments by using curly braces and index, following is the example with the result.
{{ $segments[0]; }} /* output: user */
{{ $segments[1]; }} /* output: 1 */
To get URL segments in Laravel, you can use the segments()
method from the Request class that returns all URL segments in array format.