V
V
VladimirKrasnov2021-01-16 16:07:14
Laravel
VladimirKrasnov, 2021-01-16 16:07:14

How to get pretty url in Laravel?

There is such a route and method

Route::get('/{slug}', [App\Http\Controllers\IndexController::class, 'show'])->name('show');

public function show($slug)
{
    $ad = Ad::where('slug', $slug)->firstOrFail();
    return view('ad', compact('ad'));
}


On the main page in the post preview, the button with href="{{ route('show', ['slug' => $ad->slug]) }}"

In the Ad model
public function getRouteKeyName()
{
    return 'slug';
}


In the database, when creating a record, a slug of the "new-post" type is automatically generated, and I want to get a url like localhost / new-post, but instead I get 404

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexander Talalaev, 2021-01-16
@neuotq

You are using getRouteKeyName(), you then need to change the show method, something like this:

public function show($ad)
{   
    return view('ad', compact('ad'));
}

and in the router then also for beauty
Route::get('/{ad}', [App\Http\Controllers\AdController::class, 'show'])->name('show');

Or, remove getRouteKeyName, with which you set the field by which the desired model is calculated (by default, this is id)

F
FANTASANTA, 2021-01-19
@FANTASANTA

In the route, drop this code to the very bottom

Route::get('/{slug}', [App\Http\Controllers\IndexController::class, 'show'])->name('show');

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question