Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/laravel/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Laravel in_array()期望参数2是数组,当我使用if条件时给出的对象_Laravel - Fatal编程技术网

Laravel in_array()期望参数2是数组,当我使用if条件时给出的对象

Laravel in_array()期望参数2是数组,当我使用if条件时给出的对象,laravel,Laravel,我想为输出$tourCheck设置if条件,如果我的表中存在“tour\u id”,例如,对于特定用户为5,则不应用该函数,但如果存在,则应用该函数 (我的意思是用户不能多次应用此功能) 根据当前代码,根本不需要检查数组,您可以让数据库执行检查: public function addTour(Request $request, $id) { $tourCheck = DB::table('teckets') ->where('user_id', Auth::use

我想为输出$tourCheck设置if条件,如果我的表中存在“tour\u id”,例如,对于特定用户为5,则不应用该函数,但如果存在,则应用该函数 (我的意思是用户不能多次应用此功能)


根据当前代码,根本不需要检查数组,您可以让数据库执行检查:

public function addTour(Request $request, $id)
{
    $tourCheck = DB::table('teckets')
        ->where('user_id', Auth::user()->id)
        ->where('tour_id', $id)
        ->exists();

    if (! $tourCheck) {
        tecket::create([
            'user_id' => Auth::user()->id,
            'tour_id' => $id,
        ]);

        DB::table('tours')->where('id', $id)->increment('counter');

        return view('submit_tour');
    }

    return view('submit_tour')->with('message', 'you already have a tecket for this tour.');
}
你们可以通过在Tour和用户Tecket之间建立一种关系来帮助自己。然后,您还可以连接到事件中,并在创建tecket时更新巡更计数器

您甚至可以使用
first或create
执行此操作,以进一步减少此操作:

public function addTour(Request $request, $id)
{
    $tecket = tecket::firstOrCreate([
        'user_id' => Auth::user()->id,
        'tour_id' => $id,
    ]);

    if ($tecket->wasRecentlyCreated) {
        DB::table('tours')->where('id', $id)->increment('counter');
        return view('submit_tour');
    }

    return view('submit_tour')->with(...);
}

$tourCheck
不是数组,它是一个集合,wichs也是一个对象。那么如何在if条件下使用它呢?只需将
$tourCheck
toArray()
方法进行转换,该语句应该可以工作。使用foreach迭代集合时出现相同的错误。是的,谢谢,它可以工作
public function addTour(Request $request, $id)
{
    $tecket = tecket::firstOrCreate([
        'user_id' => Auth::user()->id,
        'tour_id' => $id,
    ]);

    if ($tecket->wasRecentlyCreated) {
        DB::table('tours')->where('id', $id)->increment('counter');
        return view('submit_tour');
    }

    return view('submit_tour')->with(...);
}