cviebrock / eloquent-sluggable在getSlug()上返回null

时间:2014-07-19 01:17:34

标签: php laravel laravel-4 eloquent slug

尝试cviebrokc/eloquent-sluggable我尝试通过刀片视图访问Eloquent,回显出要链接的帖子。使用sqlite的数据库表有一个slug列,但通过Eloquent获取帖子并转储$post->getSlug()返回NULL。它的设置如下:

在我的刀片视图中:

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

在我的Posts.php模型中:

<?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',
    );
}

我应该将其指定为新实例,如果是,如何?或者我该怎么做呢?

1 个答案:

答案 0 :(得分:0)

发现$post->getSlug()仅指定了slug字段。要获取slug,将其保存到数据库并显示给用户,您需要使用sluggify()创建slug,然后自己将其存储在数据库中。从模型做它看起来像这样

//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
}