Search code examples
phplaravellaravel-4eloquentslug

cviebrock/eloquent-sluggable returns null on getSlug()


Trying out cviebrokc/eloquent-sluggable I've tried accessing the Eloquent through a blade view, echoing out the slug of a post to link to. The database table, using sqlite, has a slug column but getting the posts through Eloquent and dumping a $post->getSlug() returns NULL. It's setup as following:

In my blade view:

@foreach (Posts::get() as $post)
    {{ var_dump( $post->getSlug() ) }}
@endforeach

And in my Posts.php model:

<?php
use Cviebrock\EloquentSluggable\SluggableInterface;
use Cviebrock\EloquentSluggable\SluggableTrait;

class Posts extends Eloquent implements SluggableInterface{

    use SluggableTrait;

    protected $sluggable = array(
        'build_from' => 'title',
        'save_to'    => 'slug',
    );
}

Should I assign it as a new instance, if so, how? Or how would I go about doing it?


Solution

  • Found out that $post->getSlug() only gets the slug field designated. To get the slug, save it to database and show it to the user you need to create the slug with sluggify() and then store it in the database yourself. Doing it from model it would look like this

    //Check if slug is empty and generate if it isn't
    public function slugCheck()
    {
        if(empty($this->getSlug())) // Is slug empty
        {
            $this->sluggify();      // Create slug
            $this->save();          // Save slug to database
        }
        return $this->getSlug();    // return the slug to echo out
    }