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

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

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


当前回答

在你的控制器中

$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

其他回答

在if语句中检查null可以防止Laravel在查询结束后立即返回404。

if ( User::find( $userId ) === null ) {

    return "user does not exist";
}
else {
    $user = User::find( $userId );

    return $user;
}

如果找到用户,它似乎会运行双重查询,但我似乎找不到任何其他可靠的解决方案。

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

$user = User::where('email', '=', Input::get('email'))->get();
if(count($user) > 0)
{
echo "There is data";
}
else
echo "No data";
if (User::where('email', Input::get('email'))->exists()) {
    // 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的全部目的。

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

    }