I have the following db structure:

items:
id, name, user_id

users table:
id, name

user_favorites table:
id, user_id, item_id

在我的items permalink页面上,我有一个"Add to favorites"(添加到Collection 夹)按钮,可以在user_favorites行中插入新行

如果用户的Collection 夹中已经有"从Collection 夹中删除"按钮,我希望能够将其替换为"从Collection 夹中删除"按钮.

我无法理解这背后的逻辑——我是否需要判断user_favorites中是否存在一行,该行具有当前用户id和永久链接项目id?这对我不起作用:

if (Auth::user()->id) {
    if (!is_null(DB::table('user_favorites')->where('user_id', '=', Auth::user()->id)->where('item_id', '=', $item->id)->first())) {
        // remove from favorites button will show
    }
}

推荐答案

您可能想要这样的东西:

$user_favorites = DB::table('user_favorites')
    ->where('user_id', '=', Auth::user()->id)
    ->where('item_id', '=', $item->id)
    ->first();

if (is_null($user_favorites)) {
    // It does not exist - add to favorites button will show
} else {
    // It exists - remove from favorites button will show
}

Laravel相关问答推荐

Livewire 基于下拉 Select 自动填充输入框

在Laravel中URL中添加保护ID

如何通过 Eloquent 获取单个集合中每位教师的学生人数

运行Docker时,安装PHP8.1时返回错误

Laravel Livewire 组件在刷新后不会自动刷新/重新加载

使用命令行界面停止 laravel 服务器

如何通过一个 laravel 安装处理子域

Laravel transformer vs resource

Laravel 查询构建器 - 如何按别名分组,或进行原始 groupBy

file_put_content ...无法打开流:Laravel 5 中的权限被拒绝

laravel 5 - assets资源 list 中未定义 css 文件?

如何在 Laravel 中创建类别的嵌套列表?

使用 Laravel 将两个模型合并到一个分页查询中,并带有Eager加载的关系

在 Laravel 中,如何获取 *only* POST 参数?

Laravel Socialite 在本地主机上进行测试,SSL 证书问题?

在 Laravel 5 控制器中找不到类App\Http\Controllers\DB

如何在 Laravel 4 中组织不同版本的 REST API 控制器?

如何在 Laravel 5 请求类中使用有时规则

Laravel 排序集合,然后按键

Laravel Mix:更新 Node.js 依赖项