I'm currently using the save()
feature (doc) so save a child item to a parent. But the case where the child is already attached to the parent is not handled.
So I have created this:
//Validation stuff
$parent = Task::find( request('parent') );
$child = Task::find( request('child') );
if ( \DB::table('task_has_predecessors')
->where('child_id', request('child'))
->where('parent_id' , request('parent'))
->count() == 0 )
{
if ( $parent->childs()->save($child) )
{
flash('Link saved.');
}
else
{
flash()->error('Unable to create the link.');
}
}
else
{
flash()->warning('This link already exist.');
}
But I'm not a big fan of this solution... Is there a better way to achieve this without using if ( \DB::table('...')->where(...)->where(...)->count() == 0 )
?
Has laravel a magic way to manage this kind of behaviour?
I don't have any model related to the tasks_has_predecessors
table. And my relationships are made like this:
class Task extends Model
{
public function childs()
{
return $this->belongsToMany(ChecklistCategoryTask::class, 'task_has_predecessors', 'parent_id','child_id');
}
public function parents()
{
return $this->belongsToMany(ChecklistCategoryTask::class, 'task_has_predecessors' , 'child_id' , 'parent_id');
}
}
If you're trying to attach one model to another, use the attach()
method instead of save and ID instead of an object:
$parent->childs()->attach($child->id);
And if you're trying to create a new object, use findOrNew()
instead of find()
:
$child = Task::findOrNew(request('child'));
This method will create a new object if it doesn't exist yet.
From doc
$account = App\Account::find(10);
$user->account()->associate($account);
$user->save();