Laravel save () if the relation already exists

I am currently using the save()( doc ) function to save a child element to a parent element. But the case when the child is already attached to the parent object is not processed.

So, I 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 )?

Does laravel have a magical way to control this behavior?


I do not have a model related to the table tasks_has_predecessors. And my relationship is 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');
    }
}
+4
source share
2 answers

, attach() :

$parent->childs()->attach($child->id);

, findOrNew() find():

$child = Task::findOrNew(request('child'));

, .

+1

.

$account = App\Account::find(10);
$user->account()->associate($account);
$user->save();
-1

Source: https://habr.com/ru/post/1692411/


All Articles