我刚来拉拉维尔。如何查找是否存在记录?

$user = User::where('email', '=', Input::get('email'));

我能做什么来查看$user是否有记录?


当前回答

$email = User::find($request->email);
If($email->count()>0)
<h1>Email exist, please make new email address</h1>
endif

其他回答

创建下面的方法(为自己),以检查给定的记录id是否存在于Db表中。

private function isModelRecordExist($model, $recordId)
{
    if (!$recordId) return false;

    $count = $model->where(['id' => $recordId])->count();

    return $count ? true : false;
}

// To Test
$recordId = 5;
$status = $this->isModelRecordExist( (new MyTestModel()), $recordId);

有帮助!

if (User::where('email', 'user@email.com')->first()) {
    // It exists
} else {
    // It does not exist
}

如果只需要检查是否存在,请使用first(),而不要使用count()。

First()更快,因为它检查单个匹配,而count()计数所有匹配。

Laravel 6或顶部:写表名,然后给出where子句条件,例如where('id', $request->id)

 public function store(Request $request)
    {

        $target = DB:: table('categories')
                ->where('title', $request->name)
                ->get()->first();
        if ($target === null) { // do what ever you need to do
            $cat = new Category();
            $cat->title = $request->input('name');
            $cat->parent_id = $request->input('parent_id');
            $cat->user_id=auth()->user()->id;
            $cat->save();
            return redirect(route('cats.app'))->with('success', 'App created successfully.');

        }else{ // match found 
            return redirect(route('cats.app'))->with('error', 'App already exists.');
        }

    }

最简单的方法

    public function update(Request $request, $id)
{


    $coupon = Coupon::where('name','=',$request->name)->first(); 

    if($coupon->id != $id){
        $validatedData = $request->validate([
            'discount' => 'required',   
            'name' => 'required|unique:coupons|max:255',      
        ]);
    }


    $requestData = $request->all();
    $coupon = Coupon::findOrFail($id);
    $coupon->update($requestData);
    return redirect('admin/coupons')->with('flash_message', 'Coupon updated!');
}

我认为下面的方法是达到同样目的的最简单的方法:

    $user = User::where('email', '=', $request->input('email'))->first();
    if ($user) {
       // user exist!
    }else{
       // user does not exist
    }