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

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

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


当前回答

检查记录是否存在的有效方法必须使用is_null方法来检查查询。

下面的代码可能会有帮助:

$user = User::where('email', '=', Input::get('email'));
if(is_null($user)){
 //user does not exist...
}else{
 //user exists...
}

其他回答

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.');
        }

    }

最短工作选项:

// if you need to do something with the user 
if ($user = User::whereEmail(Input::get('email'))->first()) {

    // ...

}

// otherwise
$userExists = User::whereEmail(Input::get('email'))->exists();

在你的控制器中

$this->validate($request, [
        'email' => 'required|unique:user|email',
    ]); 

在您的视图-显示已经存在的消息

@if (count($errors) > 0)
    <div class="alert alert-danger">
        <ul>
            @foreach ($errors->all() as $error)
                <li>{{ $error }}</li>
            @endforeach
        </ul>
    </div>
@endif

要知道是否有记录是很简单的

$user = User::where('email', '=', Input::get('email'))->get();
if(count($user) > 0)
{
echo "There is data";
}
else
echo "No data";
$user = User::where('email', request('email'))->first();
return (count($user) > 0 ? 'Email Exist' : 'Email Not Exist');