I would like to add nice Slug
URL to my Laravbel Project. I currently am using ID numbers.
My goal is to continue using Numbers but also to use Slugs for better SEO URL's. So either a Slug or an ID will load the proper page.
Below is my current Route
that uses an ID number to load a record.
// View Campaign Details/Profile/Map View
Route::any("/campaign/{id}", array(
"as" => "campaign/{id}",
"uses" => "CampaignController@getCampaignMap"
));
To be able to add Slug support in Laravel 4. I believe I need to add a slug database column to my campaigns table.
How would I go about editing my Route to work with an ID number of a slug string?
Also since I am only wanting to use slug on a couple sections of my application, how would I do my.htaccess for this, or is an.htaccess even required?
$request->id; You can get id from POST method like this. public function getDetail(Requests $rq){ $product = Product::where('id',$rq->id)->get(); } .
$slugs = explode("/", $_GET['params']); This will give you an array filled with every element in your URL. This allows you to use each element as you require.
I wouldn't pass two parameters to your function, just treat it like an ID in both cases. You'll need to add a "slug" column to your db if you haven't already and make sure those values are unique just like an id. Then in your controller you can do something like this:
public function getCampaignMap($id){
//look for the campaign by id first
$campaignmap = Campaign::find($id);
//if none is found try to find it by slug instead
if(!$campaignmap){
$campaignmap = Campaign::where('slug','=',$id)->firstOrFail();
}
return View::make('campaignmap.show', compact('campaignmap'));
}
You could also save yourself a query in some cases by checking to see if the id is numeric and then just look for it by slug if it's not numeric such as:
public function getCampaignMap($id){
//look for the campaign by id if it's numeric and by slug if not
if(is_numeric($id)){
$campaignmap = Campaign::find($id);
}else{
$campaignmap = Campaign::where('slug','=',$id)->firstOrFail();
}
return View::make('campaignmap.show', compact('campaignmap'));
}
There is already a popular package that handle slugs and its possible issues: https://github.com/cviebrock/eloquent-sluggable
It can handle uniqueness adding an id suffix to previously used slugs, detect if you want to overwrite soft-deleted slugs, and some other customs configs.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With