wim91's avatar

Is it possible to check the execution of the attach() function?

Hello everyone. I can't find any information, is it possible to check the filling of the pivot table in the same way as

if($data->save()){
	//true
}else{
	//false
}

I tried like this

...
$add_prod_tag = Product::find($req->id_pr);
        if($req->tag_list){
            if($add_prod_tag->tags()->attach($req->tag_list)){
                return 'success';
            }else{
                return 'error';
            }
        }

A relationship record is added to the pivot table, but 'error' is always returned.

0 likes
2 replies
Glukinho's avatar

attach() returns void which means its result will always be evaluated as false in conditional statement.

If something is wrong with attaching, an exception will be thrown.

Why you need to check for success/error? On success, your code will continue executing. On error, an exception will be thrown. You may catch the exception and do whatever you like, or rely on Laravel exception handler.

1 like

Please or to participate in this conversation.