Reputation: 27
I'm trying to make my own simple CMS for laravel. I can add pages now and show them the only problem I have is the page url.
Route:
Route::group(array('prefix' => 'admin', 'before' => 'auth.admin'), function()
{
Route::resource('pages', 'App\Controllers\Admin\PagesController');
}
Now this is my link: http://domain.com/admin/pages/2 to access my page with id 2, in my database I have a slug column how can I change the link to the slug that belongs to id 2 so I get the following link:
Hope you can help me !
Upvotes: 2
Views: 4126
Reputation: 1065
In Laravel 9, you could have probably used Model Binding to achieve that.
When using resource route controllers...
Route::resource('/blog', 'AnimeBlogController', ['except' => ['show']]);
Route::get('/blog/{anime}', 'AnimeBlogController@show');
Make sure that the 'custom url' is being generated and store somewhere to be used as the url. For example the title 'Elon musk goes to the moon may be stored as' elon-musk-goes-to-the-moon
We accomplish this by
Controller
'slug' => Str::slug($request->input('blog_title'))
Str::slug
If you would like model binding to always use a database column other than id when retrieving a given model class, you may override the getRouteKeyName method on the Eloquent model:
* Get the route key for the model.
*
* @return string
*/
public function getRouteKeyName()
{
return 'slug';
}
public function show(Anime $anime)
Anime being the name of the table in my database and $anime
referencing Route::get('/blog/{anime}'
Upvotes: 0
Reputation: 2581
The route you need to set up is
Route::get('{slug}', 'App\Controllers\Admin\PagesController@show');
Then in your controller
public function show($slug)
{
$page = Page::where('slug', '=', $slug)->get();
return View::make('your.template')->withPage($page);
}
Upvotes: 2