pavlen's avatar

Create dinamic routes for News

HI, is there a way to create dinamic routes for news items ?

In my table I have fileds:

Id           Title                           Text

1            FIrst news                 Bla,Bla,bla

Currently, in my routes i use:

Route::get('/news/{id}/full-text','FrontController@getNews');

In Front Controller :

public function getNews($id){

$news = News::findOrFail($id);

return view('news')->with(compact('news');

}

And all working fine, except url is not fine:

So,currently URL will be : www.domain.com/news/1/full-text

Is there a way, to create dinamic routes like this :

 www.domain.com/news/first-news

To use name of news (title row in Db),to create friendly url ?

Thanks, Pavle

0 likes
1 reply
Cronix's avatar

Store a slug column for the article title in the db that gets created at the time of creating/saving the news item. Laravel has a str_slug() helper to create it (removes spaces, adds dashes, etc). https://laravel.com/docs/5.7/helpers#method-str-slug

Then your route could just be

Route::get('/news/{slug}', 'YourController@slugMethod');

And you'd just search on that column

public function slugMethod($slug) {
    $article = News::where('slug', $slug)->firstOrFail();
}

There is also a way to set laravel up to automatically retrieve it for you, using the slug column. This is much easier to set up and then you never need to manually query things like $news = News::findOrFail($id);. It does it automatically. Look into Route Model Binding: https://laravel.com/docs/5.7/routing#route-model-binding

2 likes

Please or to participate in this conversation.