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

cbil360's avatar

Starting session after authentication

Hello, I am implementing a login authentication module for my application using laravel 5. routes.php

// creating a route for login
Route::get('login','LoginController@index');
Route::post('login','LoginController@authUserPass');

I have a model Login.php in which I have the following code for authentication

public function authUserPass(CreateLoginRequest $request)
    {   
         $checkUser = Login::where('email',$request->email)->get();
         if (!$checkUser->isEmpty()){
        Session::put('email',$request->email);   //Update
             return view('login.dashboard');
            }
              else{
              return "error";
          }
    }

Now I want to start the session for the user and redirect him to the dashboard view(Redirection works fine).I need help with sessions and calling session objects.

Update:I added the user email in session here and I was able to get it on dashboard,but is the approach correct?

For example: When I redirect view('dash.blade.php') how can I create and access the session variables there? so that I can fetch the user info on dashboard.

Also I would like comments on, if the above code for authentication is the right way to go as I also have to use it as an API for mobile app

0 likes
14 replies
khoanguyenme's avatar

Why you are not using Laravel Auth Facades ?

Auth::login($usermodel, $remember = true)

And then (if you're create a API), you can have a route like

Route::get('me', 'UserController@me');
class UserController {
    
    public function me()
    {
        return \Auth::user();
    }
}

remember to protect that route with middleware or filter (L4.2)

cbil360's avatar

Hey @khoanguyenme I am pretty new and dont have much idea on Auth facades,can you point me to a good example for reference? I am using L5 and not 4.2 Where do I need to mention the below and login would be my current model if I am not wrong.Please correct

Auth::login($usermodel, $remember = true)

And will it also solve the session?I mean where do I start setting my session variables?

cbil360's avatar

@blackbird Yes I have went through laracasts,but till the 11-12 video i did not find the implementation but the explanation about the traits and facades involced in the default example shipped with L5.

Well referring the docs on authentication I have moved ahead and implemented but stuck at a point.

public function authenticate(CreateLoginRequest $request)
 {
 if(Auth::attempt(['email'=>$request->email,'password'=>$request->password]))
        {
            $request->email;
            $request->password;
            return redirect()->intended('login.dashboard');
        }
}

in the DB I have the record with the email and hashed password using Hash::make('password').

id: "1",
 email: "sachita@gmail.com",
 password: "$2y$10$Dn6j/pKZ6ogzT.oePgIVy.2GIehMnQ69YMjRgXSkxNoCgVP0PiC6S", //hashed value of password

But I am not redirected to the dashboard.I am not entering the code block after auth i.e auth is failing.Anything missing?

bobbybouwmann's avatar

I don't understand what you are trying to do here! You log in using Auth::attempt which is fine.

Then you instantiate two variables of the $request object which are doing nothing...

Let's say you have a route like this

Route::get('dashboard', ['as' => 'login.dashboard', 'uses' => 'DashboardController@index']);
//              URL                   ROUTE NAME                      ROUTE ACTION

If you want to redirect to a route name you need to do it like this

return redirect()->route('login.dashboard''); // Redirect to the route name

If you want to redirect to an url then you can use your way

return redirect()->intended('dashboard'); // Redirect to the route url 
1 like
cbil360's avatar

@blackbird Sorry,the two variables were echoed just to check if I enter the if block(which I am not).

echo $request->email; Actually the authentication is failing not redirection.

My routes.php is

Route::get('login','LoginController@index');
Route::post('login','LoginController@authenticate');
Route::get('dashboard','DashboardController@index');

Updated my authe method

 if(Auth::attempt(['email'=>$request->email,'password'=>$request->password]))
        {
            return redirect()->route('login.dashboard');
          
        }

But still the authentication fails.

bobbybouwmann's avatar

This should just work fine! There is a possibility that you didn't enter the correct password of course!

Why don't watch the complete serie before you start working by yourself. The serie really explains you how to get from nothing to something cool!

cbil360's avatar

@blackbird I have some time constraints and hence trying to push things. Just to confirm I used Hash::make('password'). to hash the password. Does auth make use of the same function to check to hashed password? The documentation says it,but just to make sure I am not going wrong there!

bobbybouwmann's avatar

Yea it is! I think we need more information to help you!

Are you sure you are sending the correct data to the function. What happens when you do this

public function authenticate(CreateLoginRequest $request)
{
    dd($request->all()) // This will echo out all the values that are posted by the browser

    if (Auth::attempt(['email'=>$request->email,'password'=>$request->password]))
    {
        return redirect()->route('login.dashboard');
    }
}

Can you also post your CreateLoginRequest class?

cbil360's avatar

@blackbird Yes if I print the request variables I do get the values.

array:3 [▼
  "_token" => "aOISXy52vKBiWFedHlzQ8GNuUjCjiCIO5ZCMKF5t"
  "email" => "sachistaware@gmail.com"
  "password" => "password"
]

CreateLoginRequest class

<?php namespace App\Http\Requests;

use App\Http\Requests\Request;

class CreateLoginRequest extends Request {

    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'email'=>'required|email',
            'password'=>'required'
        ];
    }

}

cbil360's avatar

@blackbird I dont know what was the issue but I recreated the database and it worked.Thank you for the help till now.

I would like to know now what would be the call from my API if I have to trigger a login from an mobile app? My current LoginController is as below.

class LoginController extends Controller {

    public function index()
    {
        return view('login.hexalogin');
    }

    public function authenticate(CreateLoginRequest $request)
    {
       // dd($request->all());
        if(Auth::attempt(['email'=>$request->email,'password'=>$request->password]))
        {
            return redirect()->intended('dashboard');

        }else
        {
            return view('errors.503');
        }
    }

}
cbil360's avatar

@blackbird Ok.Yes I do have a database created for the above feature,I hope he laracast covers the auth feature for an app.

One more issue ran into is inserting details using tinker. When I create a model using php artisan make:model model_name

It also creates a new migration,but I already had created a migration earlier and performed

php artisan migrate

But still I end up with two migrations.I saw the cast and it only creates a model if we already have a migration. Here is the snippet from my console

PS C:\wamp\www\laravelRouting> php artisan make:model Login
Model created successfully.
Created Migration: 2015_03_20_111745_create_logins_table

I already had a migration for login with name create_login_table but this generated another one instead of using the exiting.

bobbybouwmann's avatar

This is a feature of Laravel. When you create a model, it will automatically create a migration for you.

If you don't want that simply run this

php artisan make:model User --no-migration
1 like

Please or to participate in this conversation.