Php Mutator正在将slug保存到DB,但不是实际的标题-Laravel
我在Laravel7.24上,现在我有一个blogs表、模型和控制器。我正在打电话给Php Mutator正在将slug保存到DB,但不是实际的标题-Laravel,php,laravel,Php,Laravel,我在Laravel7.24上,现在我有一个blogs表、模型和控制器。我正在打电话给/slug,并试图使用mutator和雄辩的create()将一篇博客文章保存为测试。奇怪的是,对于我的mutator,它将slug保存到DB中,但DB中的title单元格保存为空字符串。如果我让mutator为标题工作,那么它会保存标题,但是slug会保存为空字符串。为什么它只能拯救其中一个 博客迁移: public function up() { Schema::create('blo
/slug
,并试图使用mutator和雄辩的create()
将一篇博客文章保存为测试。奇怪的是,对于我的mutator,它将slug保存到DB中,但DB中的title单元格保存为空字符串。如果我让mutator为标题工作,那么它会保存标题,但是slug会保存为空字符串。为什么它只能拯救其中一个
博客迁移:
public function up()
{
Schema::create('blogs', function (Blueprint $table) {
$table->id();
$table->string('title');
$table->string('post');
$table->string('postExcerpt');
$table->string('slug')->unique();
$table->string('user_id');
$table->string('featuredImage');
$table->string('metaDescription');
$table->integer('views')->default(0);
$table->timestamps();
});
}
控制器方法
public function slug()
{
return Blog::create([
'title' => 'This is a nice title',
'post' => 'some post',
'postExcerpt' => 'some post here',
'user_id' => 11,
'metaDescription' => 'some meta info here',
]);
}
博客模式:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Str;
class Blog extends Model
{
protected $fillable = [
'title',
'post',
'postExcerpt',
'slug',
'user_id',
'featuredImage',
'metaDescription',
'views'
];
public function setSlugAttribute($title){
$this->attributes['slug'] = $this->uniqueSlug($title);
}
private function uniqueSlug($title)
{
$slug = Str::slug($title, '-');
$count = Blog::where('slug', 'LIKE', "{$slug}%")->count();
$newCount = $count > 0 ? ++$count : '';
return $newCount > 0 ? "$slug-$newCount" : $slug;
}
}
你没有发送任何数据给你的控制器内的变异人。您需要执行类似于
'slug'=>$post->title
(或者'slug'=>“这是一个很好的标题,
,根据您的示例)的操作,以便正确调用mutator,然后执行您告诉它的操作。您得到的是默认值
错误,因为它跳过了列填充,因为它没有被任何数据水合。您没有发送任何数据给控制器内的mutator。您需要执行类似于'slug'=>$post->title
(或者'slug'=>“这是一个很好的标题,
,根据您的示例)的操作,以便正确调用mutator,然后执行您告诉它的操作。您得到的是默认值
错误,因为它跳过了列填充,因为没有使用任何数据进行水合。这是因为Laravel elequent不知道您打算将slog列与其他列一起保存,因为您已将其设置为可空。按如下所示修改您的工作方法
public function slug()
{
return Blog::create([
'title' => 'This is a nice title',
'slug' => 'This is a nice title',
'post' => 'some post',
'postExcerpt' => 'some post here',
'user_id' => 11,
'metaDescription' => 'some meta info here',
]);
}
这是因为Laravel elequent不知道您打算将slog列与其他列一起保存,因为您已将其设置为nullable。按如下所示修改您的工作方法
public function slug()
{
return Blog::create([
'title' => 'This is a nice title',
'slug' => 'This is a nice title',
'post' => 'some post',
'postExcerpt' => 'some post here',
'user_id' => 11,
'metaDescription' => 'some meta info here',
]);
}
正确的uniqueSlug方法,不起作用您没有发送任何数据供mutator使用。您需要执行类似于
'slug'=>$post->title
的操作,正确地使用uniqueSlug方法,不工作您没有发送任何数据供mutator使用。你需要做一些类似于'slug'=>$post->title