Laravel - 在attach()和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?

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()));
}