Skip to content
Advertisement

SESSION in laravel for page protection

I want to make a Login Registration system in laravel 8. In which User when login only can access a particular page else redirect to login page. I did this like that. what’s wrong in it.

//Login Code

 function login(Request $req){
        $results = DB::table('crud_users')
        ->where('email', '=', $req -> post('email'))
        ->where('password', '=', $req -> post('password'))
        ->get();
        foreach ($results as $value) {
            $value ->email;
            $value ->password;
            $name = $value ->name;
            $user_type = $value ->user_type;
            echo $id = $value ->id;
            session()->put('id', $id);
            session()->put('name', $name);
        }
        $req -> validate([
            'email' => 'required',
            'password' => 'required',
        ]);
        $email = $req -> input('email');
        $password = $req -> input('password');
        if ($user_type == 'admin') {
            if (($email == $value ->email) && ($password == $value->password)) {
            return redirect('admin');
            }
        } else if($user_type == 'user') {
            if (($email == $value ->email) && ($password == $value->password)) {
            return redirect('user');
        } else{
            return redirect('login');
        }
        
        
        
        // session()->flash('success','You are registered! Please login!');
        // return redirect('login');

    }
}

//Session Code

if (session()->has('id')) {
Route::get('logout','AppHttpControllersUser@logout');
Route::view('user','user');
Route::view('admin','admin');
Route::view('edit/{id}','edit/{id}');
}else{
    Route::get('/', function () {
    return view('welcome');
});

Advertisement

Answer

you can use the default authentication in laravel8 using laravel application Jetstream starter kit and use the auth() middleware to go to a particular page. you can see this [blog]1

or see the laravel’s documentation from [here]2

for your code you’re i think you’re call session by this way session() it’s wrong you should call the session class or use this way like this $request->session()->has('id')

or

Session::has('id')
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement