devs
devs

Reputation: 541

Laravel - Sending ip to the database on create and updating

So I'm trying to send the ip address of a user when two events happen

So I know how I can update and also grab the ip address, however, I don't want to copy and paste two pieces of code twice to get the same results.... So what I am asking is, how can I grab the IP once the user is loads the website, store it in a global(?) variable and then use that variable wherever I need it, for example, when the user creates the account, and when a filter checks to see if the ip is the same or not.

So for I tried to add it into my HomeController constructor, but the UserController could not find the variable, and I probably know why. So here's the code.

UserController where I would need it:

    public function createUser()
    {

        $newUser = new User;
        $newUser->username = $username;
        // get ip address
        $newUser->ip_address = $userIpAddress;
        $newUser->save();

        if (!Auth::check()) {
            Auth::login($newUser);
        } else {
            return View::make('home');
        }
        return Redirect::action('HomeController@showHome');
    }

Filter where I'd check if it's different or not

Route::filter('checkUserFilter', function() 
{
    $userIpAddress = Request::getClientIp();

    if (Auth::guest()){
        return Redirect::action('UserController@createUser');
    }  else {

        $user = Auth::user();
        return View::make('home', 
                [   'user'          => $user,
                    'userName'      => $user->username, 
                    'userId'        => $user->id, 
                    'userPass'      => $user->password
                ]
        );
    }

});

Upvotes: 1

Views: 2913

Answers (1)

Andreyco
Andreyco

Reputation: 22872

Eloquent fires multiple events and you can listen to them.
What you want is to listen to saving event which is fired every time model is created or updated (saved to database).
Here is how you can do that.

Eloquent tries to save the model and fires saving event. Since you listen to this event you get instance of the model which is being saved at that moment as the function parameter. Now you can set IP address there (or any other attribute)

// app/models/User.php

class User extends Eloquent
{
    /**
     * Listen for save event
     */
    protected static function boot()
    {
        parent::boot();

        static::saving(function($model)
        {
            $model->ip = \Request::getClientIp();
        });
    }
}

Now, the route filter.
Since you set the attribute automaticaly in event listener, it should be enough to call update method.

Route::filter('checkUserFilter', function() 
{
    if (Auth::guest()) {
        // ...
    }  else {

        $user = Auth::user();
        $user->ip = Request::getClientIp();
        $user->update();

        // ...
    }

});

Upvotes: 3

Related Questions