3
votes

In Laravel 5.2, i need to do something while the authentication process is being triggered. (Not "after" the login.)

Here are what i have done.

In EventServiceProvider.php:

protected $listen = [
  'Illuminate\Auth\Events\Attempting' => ['App\Listeners\UserLoginAttempt@handle'],
];

In app/Listeners/UserLoginAttempt.php:

<?php
namespace App\Listeners;

use Illuminate\Http\Request;
use Illuminate\Auth\Events\Login;
use Carbon\Carbon;
use Auth;

class UserLoginAttempt
{
    public function __construct()
    {

    }

    public function handle($event)
    {
        dd(Auth::user());
        exit;
    }
}

This always returns null.

** In fact, i have one "custom" field in the Login form, of which i need to capture from the above Event Handler. (I need to check something before actual Login event is done.)

  • How do i capture the Auth::user() from this (Illuminate\Auth\Events\Attempting) Handler please?
  • (In other words) How do i talk with the Login Form from the (Illuminate\Auth\Events\Attempting) Handler?
  • OR ----- Is the Auth::user() object created ONLY AFTER the login is fully processed? Which means i can not get it while in "attempting" stage?

Because i need to capture the login elements first, and if it is something "unauthorized" (after some calculations done in Handler), then i need to terminate the login attempt and route back to the login form from here.. by carrying the Failing Message along.

Please let me know what i'm missing here. Thank you.

2
According to documentation you are right that Auth::user() object created once user is authenticated. - Abbasi
@Abbasi Thanks for the helps. In this case, what do you think is the proper way to grab the Elements submitted from the Login Form please? (Using $_GET["my_custom_field"] like this ugly?) - 夏期劇場
Use Request e.g. $my_custom_field = $request->input('my_custom_field'); if you provide your controller method where you are trying to achieve this would be quite easy to guide further. - Abbasi
Hi @Abbasi, thanks for all your helps with Laravel knowledge :D Could you please kindly help on this issue also (please?) : stackoverflow.com/questions/37180161/… (Big thanksss!) :D - 夏期劇場
Welcome, I'm adding an answer for it, might help someone else too. - Abbasi

2 Answers

2
votes

According to documentation you are right that Auth::user() object is only created when user is authenticated.

2
votes

Inside the Illuminate\Auth\Events\Attempting listener; you can capture the form field by

public function handle(Attempting $event)
{
      //return dd($event); // will echo all fields
      $event->credentials['email']; // capturing the email field
}

you can also use the User model and then access the user table in DB, to get / check a user field in DB...