Laravel在保存之前产生slu ..

Sve*_*art 10 php laravel laravel-5

我试图在这个wondefull网站的帮助下学习laravel 5 .对于我的活动模型,我想在将一个保存到我的数据库之前生成slug,所以我创建了以下模型.

<?php namespace App;

use Illuminate\Database\Eloquent\Model;

class Activity extends Model {

    protected $table = 'activitys';

    protected $fillable = [
        'title',
        'text',
        'subtitle'
    ];

    // Here I want to auto generate slug based on the title
    public function setSlugAttribute(){
        $this->attributes['slug'] = str_slug($this->title , "-");
    }
    //    
}
Run Code Online (Sandbox Code Playgroud)

但是当我在Activity模型的帮助下保存一个对象时没有填充slug,我尝试将它更改为$ this-> attributes ['title'] ="test"进行测试,但它没有运行.我还尝试将参数$ title,$ slug添加到setSlugAttribute()但它没有帮助.

我做错了什么,有人可以解释setSomeAttribute($ whyParameterHere)的一些示例中使用的参数.

注意:我的数据库中有一个slug字段.

正如user3158900所建议的,我尝试过:

public function setTitleAttribute($title){
    $this->title = $title;
    $this->attributes['slug'] = str_slug($this->title , "-");
}
//
Run Code Online (Sandbox Code Playgroud)

这使我的标题字段为空,但按照我想要的方式保存了slug,为什么$ this-> title为空呢?如果我删除$ this-> title = $ title; 标题和slug都是空的

use*_*496 22

我相信这不起作用,因为你没有尝试设置一个slug属性,所以函数永远不会被击中.

我建议$this->attributes['slug'] = ...你在你的setTitleAttribute()功能中进行设置,这样每当你设置一个标题时它就会运行.

否则,另一种解决方案是为您的模型创建一个保存事件,并将其设置在那里.

编辑:根据评论,还需要在此功能中实际设置title属性...

public function setTitleAttribute($value)
{
    $this->attributes['title'] = $value;
    $this->attributes['slug'] = str_slug($value);
}
Run Code Online (Sandbox Code Playgroud)


小智 7

你有两种方法:

1. 在您的控制器方法中添加 localy 这一行:

$request['slug'] = Str::slug($request->title);
Run Code Online (Sandbox Code Playgroud)

例子:

//use Illuminate\Support\Str;

public function store(Request $request)
{
    $request['slug'] = Str::slug($request->title);

    auth()->user()->question()->create($request->all());
    return response('Created!',Response::HTTP_CREATED);
}
Run Code Online (Sandbox Code Playgroud)

2.将它添加到您的模型中以在db中每次保存时检查它

//use Illuminate\Support\Str;

protected static function boot() {
    parent::boot();

    static::creating(function ($question) {
        $question->slug = Str::slug($question->title);
    });
}

Run Code Online (Sandbox Code Playgroud)

例子:

<?php

namespace App\Model;

use Illuminate\Database\Eloquent\Model;
use App\User;
use Illuminate\Support\Str;

class Question extends Model
{
    protected static function boot() {
        parent::boot();

        static::creating(function ($question) {
            $question->slug = Str::slug($question->title);
        });
    }

//The rest of methods

Run Code Online (Sandbox Code Playgroud)

在每种方式中,您都必须在类声明之前添加此代码:

use Illuminate\Support\Str;
Run Code Online (Sandbox Code Playgroud)


Dil*_*rth 6

实现这一目标的一种方法是挂钩模型事件.在这种情况下,我们想要在创建时生成一个slug .

/**
 * Laravel provides a boot method which is 'a convenient place to register your event bindings.'
 * See: https://laravel.com/docs/4.2/eloquent#model-events
 */
public static function boot()
{
    parent::boot();

    // registering a callback to be executed upon the creation of an activity AR
    static::creating(function($activity) {

        // produce a slug based on the activity title
        $slug = \Str::slug($news->title);

        // check to see if any other slugs exist that are the same & count them
        $count = static::whereRaw("slug RLIKE '^{$slug}(-[0-9]+)?$'")->count();

        // if other slugs exist that are the same, append the count to the slug
        $activity->slug = $count ? "{$slug}-{$count}" : $slug;

    });

}
Run Code Online (Sandbox Code Playgroud)

您还需要将以下内容添加到应用程序的别名列表(app.php):

'Str' => Illuminate\Support\Str::class,
Run Code Online (Sandbox Code Playgroud)


Mah*_*alt 5

您可以使用我使用的这个包https://github.com/cviebrock/eloquent-sluggable或检查它如何在模型保存上应用观察者以及它如何生成唯一的 Slug,然后执行相同的操作。