In saving a model, I have an error thats the slug attribute doesn't have a default value. I had created a setSlugAttribute mutators but it gived me the error again.
//Controller save method inside
* * *
Task::create($request->all());
* * *
//Task model
public function setSlugAttribute(){
$this->attributes['slug'] = Str::slug($this->title, '-');
}
How can I fix it? It does fix by using observe(saving), doesn't it? Another idea?
I have created an TaskObserver and I set it in ServiceProvider.
In the observer, updated(Task $task) and updating(Task $task) methods didn't work ! But the created method works.
//Update method inside:
$array = $request->all(['title', 'description', 'deadline', 'budget','guest_token']);
$task = Task::where('id',$request->id)->update($array);
//I am waiting working of udate observer but it don't
//TaskObserver
public function updating(Task $task)
{
dd("updating");
}
public function updated(Task $task)
{
dd("updated");
}
I have solved this problem by doing the following:
//when I assigned it to a variable and then calling update method, it worked
$task = Task::where('id',$request->id)->first();
$update = $task->update($request->all(['title', 'description', 'deadline', 'budget','guest_token']));
So every time a Task
is created or updated you want the slug
column to be auto-populated from title
column.
Accessors are not good for this. What you want is observers. For observers you have two choice: closure based or class based. Considering your use case is not too complex, I'd choose closure based observers.
You need two events creating
and saving
to handle it when the model is first creating, and when model is updating. So your task model should look like this:
<?php
class Task extends Model
{
protected static function creating()
{
static::creating(function ($task) {
$task->slug = Str::slug($task->title, '-');
});
static::saving(function ($task) {
$task->slug = Str::slug($task->title, '-');
});
}
}
This should do the trick.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.