Answer the question
In order to leave comments, you need to log in
Laravel 5.8. Why doesn't the mutator work?
Hello!
I have a database table with a "slug" field. In migration:
Since the field must be unique and generated automatically when a new record is added, I use a mutator in the model:$table->string('slug');
public function setSlugAttribute($value) {
$this->attributes['slug'] = Str::slug(mb_substr($this->manufacture, 0, 60) . "-", "-");
}
public function store(Request $request)
{
$manufacture = Manufacture::create($request->all());
return redirect()->route('admin.manufactures.index');
}
SQLSTATE[HY000]: General error: 1364 Field 'slug' doesn't have a default value
(SQL: insert into `manufactures`
(`manufacture`, `description`, `meta_description`, `meta_keywords`, `country`)
values
(Производитель 2, описание, meta description, meta keywords, Россия))
protected $fillable = [
'manufacture',
'slug',
'country',
'image',
'description',
'meta_description',
'meta_keywords',
];
Answer the question
In order to leave comments, you need to log in
Why should he work? The mutator mutates the value when it is set, either explicitly or implicitly.
there is not even an attempt to store the value of the 'slug' field, although it is declared in the model in the $fillable arrayI recommend reading the documentation for what this field was invented for. Certainly not for extracting data from the request...
Either you didn't pass $_POST['slug'] / $_GET['slug']
Then you pass $value to slug, and then you don't use it - you take $this->manufacture. It is most likely empty, because you are creating a new model
1) that is, it will try SELECT * FROM manufacturers WHERE ... (an empty query to the database if the database is at 300 ping in the cloud, + 350ms to create the page)
2) even if it is will be done on an existing model - of course it will do a SELECT * and pull out all the fields for you. To do this, be sure to use with();
Stop what? you are in manufacture.php, there you have setSlug() and inside $this->manufacture.... Do you have a parent/child relationship inside this table? Where did you decide to get $this->manufacture from?
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question