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

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

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


当前回答

最好的解决方案之一是使用firstOrNew或firstOrCreate方法。文档中有更多关于这两者的详细信息。

其他回答

这是一个简单的代码来检查电子邮件是否存在数据库


    $data = $request->all();
    $user = DB::table('User')->pluck('email')->toArray();
    if(in_array($user,$data['email']))
    {
    echo 'existed email';
    }

简单,舒适和易于理解的Validator

class CustomerController extends Controller
{
    public function register(Request $request)
    {

        $validator = Validator::make($request->all(), [
            'name' => 'required|string|max:255',
            'email' => 'required|string|email|max:255|unique:customers',
            'phone' => 'required|string|max:255|unique:customers',
            'password' => 'required|string|min:6|confirmed',
        ]);

        if ($validator->fails()) {
            return response(['errors' => $validator->errors()->all()], 422);
        }

这取决于您是想在之后使用用户,还是只检查是否存在一个用户。

如果用户对象存在,你想使用它:

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

如果你只是想检查一下

if (User::where('email', '=', Input::get('email'))->count() > 0) {
   // user found
}

或者更好

if (User::where('email', '=', Input::get('email'))->exists()) {
   // user found
}

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', request('email'))->first();
return (count($user) > 0 ? 'Email Exist' : 'Email Not Exist');