Home > Blockchain >  Laravel user authentication issue
Laravel user authentication issue

Time:06-23

My problem is that when user finishes the registration process and is sent to the dashboard view he's not in the authenticated state, dd(auth()->user()); returns null. Data about the user does get saved successfully in the database. Why is the user not getting authenticated?

RegisterController

public function store(Request $request)
    {
        //1. Validation
        $this->validate($request, [
            'name' => 'required|max:255',
            'username' => 'required|max:255',
            'email' => 'required|email|max:255',
            'password' => 'required|confirmed',
        ]);
        //2. Store user
        User::create([
            'name' => $request->name,
            'username' => $request->username,
            'email' => $request->email,
            'password' => Hash::make($request->email),
        ]);

        //3. Sign the user in
        auth()->attempt($request->only('email', 'password'));

        //4.Redirect
        return redirect()->route('dashboard');
    }
}

DashboardController

public function index()
    {
        dd(auth()->user());
        return view('dashboard');
    }

CodePudding user response:

You need to change some code of your store method:

use Illuminate\Support\Facades\Auth;

class RegisteredController extends Controller
{
   
    public function store(Request $request)
    {
         $this->validate($request, [
            'name' => 'required|max:255',
            'username' => 'required|max:255',
            'email' => 'required|email|max:255',
            'password' => 'required|confirmed',
        ]);

        $user = User::create([
            'name' => $request->name,
            'username' => $request->username,
            'email' => $request->email,
            'password' => Hash::make($request->email),
        ]);

        Auth::login($user);  //you need authenticate by $user obj

         return redirect()->route('dashboard');
    }
}

I just imported Auth Facade and used Auth::login($user) on the created user that I got in $user variable.

Make sure your all params i.e. 'name', 'username', 'email' etc must added in User model fillable array property.

  • Related