user3535369
user3535369

Reputation: 27

Laravel Resource Controller Slug

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:

http://domain.com/slug

Hope you can help me !

Upvotes: 2

Views: 4126

Answers (2)

OBrien Evance
OBrien Evance

Reputation: 1065

In Laravel 9, you could have probably used Model Binding to achieve that.

When using resource route controllers...

  1. In web.php use except to single out the action you want to use with custom url
Route::resource('/blog', 'AnimeBlogController', ['except' => ['show']]);

Route::get('/blog/{anime}', 'AnimeBlogController@show');
  1. 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

  2. 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';
}

4. Notice my route has a blog/{anime} in Route::get('/blog/{anime}', 'AnimeBlogController@show');

  1. {anime} has to match the variable you set on the resource route public function show(Anime $anime)

Anime being the name of the table in my database and $anime referencing Route::get('/blog/{anime}'

  1. Finally, return the view using the slug to fetch data. (I was trying to explain Model Binding)

Upvotes: 0

RMcLeod
RMcLeod

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

Related Questions