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

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

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


当前回答

if($user->isEmpty()){
    // has no records
}

Eloquent使用集合。 参见以下链接:https://laravel.com/docs/5.4/eloquent-collections

其他回答

if (User::where('email', Input::get('email'))->exists()) {
    // 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

在laravel雄辩中,有默认的exists()方法,参考下面的例子。

if (User::where('id', $user_id )->exists()) {
    // your code...
}

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

    }
$user = User::where('email', '=', Input::get('email'))->first();
if ($user === null) {
   // user doesn't exist
}

可以写成

if (User::where('email', '=', Input::get('email'))->first() === null) {
   // user doesn't exist
}

这将返回true或false,而不分配临时变量,如果这是你在原始语句中使用$user的全部目的。