Friendly urls in Laravel , am I doing it right?

a 夏天 提交于 2019-12-11 12:11:30

问题


Here's my route :

Route::get('location/{id}/{title?}', array('as' => 'scouting_single', 'uses' => 'ScoutingController@get_single')); 

The class is simple:

public function get_single($id, $title ='') { 
    $location = new Location; 
    if(is_numeric($id)) { 
        $location = $location->find($id);
        if(isset($location)) {
            $author = User::find($location->author);                
            $meta = $location->find($id)->metakeywords;

            if($title == '') { 
                $slug = Str::slug($location->title); 
                return Redirect::to('location/'.$id.'/'.$slug);
            }


            return View::make('scoutingviews.view')->with('pagetitle', 'Location view')
                ->with('location', Location::find($id))
                ->with('author', $author)
                ->with('meta', $meta);  
        } else { 
            return Redirect::to('/')->with('message', 'That record is not available'); 
        }               
    } else { 
        return Redirect::to('404');
    }
}

Everything seems to work fine but after searching around it seems that others are doing it differently like saving the slugs to db, but I just want to include the id to the url... and make it optional to include the title slug. If the user removes the slug, it will redirect the user with the slug anyways.

I'm still learning laravel so please forgive the newbie question with regards to seo-friendliness, I just don't want /{id}/ and /{id}/{title} to count as duplicates


回答1:


If you are worried about SEO, then having a URL slug in the database is the way to go. Having the ID in the URL isn't very helpful to search engines or users. This should also simplify your code as well. In addition to that, you should take a look at Eloquent relationships where you can attach your users to locations. Instead of having

$author = User::find($location->author);

You could have

$author = $location->author;

The relationship would be a User hasMany Locations, and Location belongsTo User. This is also assuming that users can have many locations.



来源:https://stackoverflow.com/questions/21527573/friendly-urls-in-laravel-am-i-doing-it-right

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!