Novalink Novalink - 1 month ago 18
PHP Question

Laravel - Check query execution after attach() and detach()

After I execute this

$shop->articles()->attach($article_id);


or this

$shop->articles()->detach($article_id);


how do I make sure they actually get executed? In the first case it returns void, but also it saves automatically so I cannot use the save function to check it. In the second case it returns int, but what does it represent?

Answer

You do it with try/catch and DB::transaction/commit/rollback.

try{
    \DB::transaction(function() use($shop, $article_id) {
        $shop->articles()->attach($article_id);
    });

    \DB::commit();
} catch (\Exception $e) {
    \DB::rollback();

    return redirect()->back()->withErrors(collect($e->getMessage()));
}
Comments