Modify the Eloquent model
- use
SluggableInterfaceandSluggableTrait - use
SluggableTrait(Shorthand to avoid typing the whole path) - create the
$sluggablearray - important values are
build_fromandsave_to
build_from value is the field Sluggable will convert as a slug, if the title contains this value: 'this is the title' it will save the slug value in the column you specified in save_to field as 'this-is-the-title'
<?php
use Cviebrock\EloquentSluggable\SluggableInterface;
use Cviebrock\EloquentSluggable\SluggableTrait;
class Model extends Eloquent implements SluggableInterface {
use SluggableTrait;
protected $sluggable = array(
'build_from' => 'title',
'save_to' => 'slug',
'max_length' => null,
'method' => null,
'separator' => '-',
'unique' => true,
'include_trashed' => false,
'on_update' => false,
'reserved' => null,
'use_cache' => false,
);
}
Next step is to create the slug column on the database
if no add_sluggable_columns migration has been created you can do this by running
php artisan sluggable:table [table name]
If it already exist, just modify the migration and add it to the up() and down() methods
up()
Schema::table('table name', function(Blueprint $table)
{
$table->string('slug')->nullable();
});
down()
Schema::table('table name', function(Blueprint $table)
{
$table->dropColumn('slug');
});
You will need to modify your routes file to make use of the sluggable urls (especially the show() and edit() methods of a route resource.)
public function show($slug)
{
$model = Model::findBySlug($slug);
return View::make('model.show', compact('model'));
}
The only problem left is when using route names on route resources, because still model.show, model.edit will be using the [resource]/[id] routing.