saimcan
saimcan

Reputation: 1762

Laravel Event Listening

I have an issue similar to this post : Laravel - last login date and time timestamp

In short, my purpose and question is :

  1. I have a "logrecords" table in my database.
  2. My event listeners in global.php are just working on default "users" table.
  3. I want my event listeners are able to insert data on my "logrecords" table.

How can i do that :

  1. Should i configure my database tables using which are using eloquent ?
  2. Or should i change something in global.php ?

Thanks for your support.

--------------------Update--------------------

I realized that in my auth.php file, default authentication model has been set as :

'model' => 'User'

But i want to listen and work with both User and Logrecord model.So that when i try to listen events in my global.php file, laravel is automatically trying to work with User model. So that i had to configure my event listeners like that :

Part of my global.php file :

//First Example
Event::listen('auth.login', function($user)
{   
    $userLogRecord = Logrecord::firstOrCreate(array('user_id' => $user->id));
    $userLogRecord->user_id = $user->id;
    $userLogRecord->login_last_at = date('Y-m-d H:i:s');
    $userLogRecord->save();
});

//Second Example
Event::listen('auth.logout', function($user)
{    
    $userLogRecord = Logrecord::firstOrCreate(array('user_id' => $user->id));
    $userLogRecord->user_id = $user->id;
    $userLogRecord->logout_last_at = date('Y-m-d H:i:s');
    $userLogRecord->save();
});

It is working for now, but I am thinking that it's not a good idea to edit my listeners like that. My purpose is to listen and do some process with both User and Logrecord models. It serves my purpose right now but i feel like i have to improve.

Any ideas ?

Upvotes: 1

Views: 1428

Answers (1)

Eddy Ferreira
Eddy Ferreira

Reputation: 800

@DemonDrake,

If I understand correctly you simply want to add data to a "log" table? In the most simple form, the answer is "Yes you would use the eloquent ORM for that

class Log extends Eloquent {

    protected $table = 'log';

}

or perhaps query builder even. There are a number of ways this is possible. I personally suggest you check out https://laracasts.com/lessons

Upvotes: 1

Related Questions