Skip to content

Instantly share code, notes, and snippets.

@lozadaOmr
Last active August 29, 2015 14:13
Show Gist options
  • Select an option

  • Save lozadaOmr/1eef6cf8fe7c881ec594 to your computer and use it in GitHub Desktop.

Select an option

Save lozadaOmr/1eef6cf8fe7c881ec594 to your computer and use it in GitHub Desktop.
notes on how to use Eloquent-Sluggable https://github.com/cviebrock/eloquent-sluggable

Modify the Eloquent model

  1. use SluggableInterface and SluggableTrait
  2. use SluggableTrait (Shorthand to avoid typing the whole path)
  3. create the $sluggable array
  4. important values are build_from and save_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');
});

Accessing the slugs:

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment