简体   繁体   English

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

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

I want to delete a row from likes_table if the table already has a row which contain requested shop_id and user_id combination.如果表已经有一行包含请求的 shop_id 和 user_id 组合,我想从 likes_table 中删除一行。 Or, make a new row if it not exists.或者,如果不存在,则创建一个新行。

However, this following code always executes delete method (returns 204) even if there is no row.但是,即使没有行,以下代码也始终执行 delete 方法(返回 204)。

Would you give me any advice?你能给我什么建议吗?

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

I solved it myself.我自己解决了。

OK:好的:

if ($liked->isEmpty()) if ($liked->isEmpty())

NG: NG:

if (!empty($liked)) if (!empty($liked))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM