Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

idodeva's avatar

Best solution for setting the route

Hi all,

I am trying to display a view for particular user. Have the code:

public function checkLogin(Request $request){
    $this->validate($request, [
        'email' => 'required|email',
        'password' => 'required|alphaNum|min:3'
    ]);

    $user_data = array(
        'email' => $request->get('email'),
        'password' => $request->get('password')
    );

    $id = Auth::id();

    if(Auth::attempt($user_data)){
        return redirect('welcome/'.$id);
    }else{
        return back()->with('error', 'Wrong Login Details');
    }
}

function successLogin($id){
    $students = AdditionalInfoStudent::with('user')->find($id);
    $first_name = $students->first_name;
    $last_name = $students->last_name;
    $faculty_number = $students->faculty_number;

    return view('welcome', compact('first_name','last_name','faculty_number'));
}

function logout(){
    Auth::logout();
    return redirect('login');
}

What is causing the problem is the following:

$id = Auth::id();

    if(Auth::attempt($user_data)){
        return redirect('welcome/'.$id);
    

When logging in sometimes the variable id has value, but other time doesn't and the view is not displayed. How should I handle this?

Thanks in advance :)

0 likes
2 replies
adamprickett's avatar

Move $id = Auth::id(); inside your conditional block as the user won't be set until after you've called Auth::attempt():

if(Auth::attempt($user_data)){
    $id = Auth::id();

    return redirect('welcome/'.$id);
}else{
    return back()->with('error', 'Wrong Login Details');
}
idodeva's avatar

Ok. Thanks for the help :) Appreciated!

Please or to participate in this conversation.