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

Posted

技术标签:

【中文标题】如何在 Laravel 控制器中使用 null 或 empty?【英文标题】:How can I use null or empty in Laravel Controllers? 【发布时间】:2022-01-24 05:29:11 【问题描述】:

如果表已经有一行包含请求的 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());
        
    

【问题讨论】:

【参考方案1】:

我自己解决了。

好的:

if ($liked->isEmpty())

NG:

如果 (!empty($liked))

【讨论】:

以上是关于如何在 Laravel 控制器中使用 null 或 empty?的主要内容,如果未能解决你的问题,请参考以下文章