When i visit to my.site/api/genre/slug-name
In route/api.php
:
Route::prefix('genre')->group(function () {
Route::get('/{slug}', [FilmController::class,'getFilmByGenre'])->name('api_genre_film');
});
In getFilmByGenre
:
public function getFilmByGenre(Request $request, string $slug)
{
dd($slug, $request->slug, $request->get("slug")); // "slug-name" - "slug-name" - null
}
Can anyone please explain to me the difference when using $slug
, $request->slug
and $request->get("slug")
?
I'm using laravel 10.x. Thanks for your help!
The reason for this is because of the difference in Route Parameter Binding vs. It is a query parameter. On the concepts of Route Parameter Binding vs. Search Query Parameter.
The $slug
parameter gets its value directly from the route definition. It's a route parameter, bound to the URI pattern.
$request->get("slug")
tries to retrieve a value for the key "slug" from the query string. The query string is the part of the URL that comes after the ? symbol and consists of key-value pairs separated by &.
In your case, there's no "slug" key in the query string (my.site/api/genre/slug-name)
, hence $request->get("slug")
is null.
and for $reuset->slug
Laravel internally maps route parameters to properties of the request object. So if you have a route parameter named {slug}
, Laravel will automatically bind it to the $request->slug
property.
In summary:
$slug
: "slug-name" (value extracted from the route parameter)
$request->slug
: "slug-name" (When you access $request->slug
, you're accessing the same value as $slug
)
$request->get("slug")
: null (no "slug" key in the query string)