簡體   English   中英

如何在 Laravel 控制器中使用 null 或為空?

[英]How can I use null or empty in Laravel Controllers?

如果表已經有一行包含請求的 shop_id 和 user_id 組合,我想從 likes_table 中刪除一行。 或者,如果不存在,則創建一個新行。

但是,即使沒有行,以下代碼也始終執行 delete 方法(返回 204)。

你能給我什么建議嗎?

public function store(Request $request)
    {
        $liked_id = Like::where('shop_id', $request->shop_id)
            ->where('user_id', $request->user_id)
            ->get('id');
        $liked = Like::find($liked_id);
        if (!empty($liked)) {
            Like::where('shop_id', $request->shop_id)
                ->where('user_id', $request->user_id)->delete();
            return 204;
        } else {
            return Like::create($request->all());
        }
    }

我自己解決了。

好的:

if ($liked->isEmpty())

NG:

if (!empty($liked))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM