简体   繁体   中英

laravel 5.4 How do I get current user through User model? and Auth::user() dosen't work

I'm trying to get the current user through User model but it returns null.

$user = new User;
//$user = Auth::user();
$product = new Product;

$product->user_id = $user->user_id;
$product->save();

This is what I get Integrity constraint violation: 1048 Column 'user_id' cannot be null

When I tried to get it with Auth::user(), it gives same error.

This is my custom login controller..

public function auth(Request $request)
{
    $this->validate($request, [
        'email' => 'required|email|max:255',
        'password' => 'required|min:6',
    ]);

    $data = $request->only('email', 'password');

    if (Auth::attempt($data)) {
        $email = $request->email;
         $users = DB::table('users')
            ->where('email', $email)
            ->select('users.*', 'user_name')
            ->get();

        Session::put('set', $users);

        if ($users[0]->is_admin == '1') {
            return redirect()->intended('adminDashboard');
        }else{
            return redirect()->intended('dashboard');
        }
    }else{
        return back()->withInput()->witherrors(['Email or password did not match!']);
    }
}

What's wrong with this code?

请尝试: $product->user_id = Auth::id();

Change this line:

$product->user_id = $user->user_id;

to this:

$product->user_id = auth()->user()->id;

Or use relationship to create a product:

auth()->user()->product()->create($productData);

If you get current user details than user bellow code.

$loggedInUser = Auth::user();

Insert details in user table

$loggedInUser['data1'] = $data1;
$loggedInUser['data2'] = $data2;
$loggedInUser['data3'] = $data3;

Save user details

$loggedInUser->save();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM