Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting user's ip address in model

I have an ip_address field for all my tables that I'd like to popular automatically using the models. How could I set that in the models? I'm guessing I'd have to use the before_save filter for this?

like image 303
Hopstream Avatar asked Apr 14 '26 20:04

Hopstream


1 Answers

There is no reason to use a filter. The ip_address column is a column like every other. Depending on your intention you must find an matching model instance and change its ip_address column or create a new entry including the columnm.

And when you say you have the column in every table its bad style. The ip_address is assigned to a user, not to every single model. I would suggest you to create a new model called Login which includes the ip_address, user_id and the created_at and updated_at fields. The last one are generated automaticly. Then you can save the ip_address each time the user logs in. Like this in your controller:

login=Login.new
login.user=current_user
login.ip_address=request.remote_ip
login.save 
like image 170
davidb Avatar answered Apr 17 '26 08:04

davidb