Reputation: 127
I'm trying to count the amount of times a user logged in. Here's how I'm attempting to do this:
Call the user with
$user = User::find(Auth::user()->id);
After that, I'm trying to access DB for the amount of times the user logged in using
$logincount = $user->logincount;
and then I'm trying to increment the variable with this line
++$logincount;
and finally i'm trying to save the user and return a redirect to the intended page:
$user->save();
return Redirect::intended('/');
After I login and check the db, the number in the "logincount" field is not incremented and I am logged in and redirected to the correct page. I datadumped/vardumped the $user variable and it shows that the user is still 0. Not sure what the issue is, as I have just started learning to program. I would really appreciate some help. Thx!
Here's the entire function:
public function postSignIn() {
$validator = Validator::make(Input::all(), array(
'email' => 'required',
'password' => 'required'
));
if ($validator->fails()) {
//Redirect to sign in page
return Redirect::route('home')->withErrors($validator)->withInput();
} else {
//Checks if user checked true or false
$remember = (Input::has('remember')) ? true : false;
//Attempt use sign in
$auth = Auth::attempt(array(
'email' => Input::get('email'),
'password' => Input::get('password'),
'active' => 1
), $remember);
if ($auth) {
//Increment login count
$user = User::find(Auth::user()->id);
$logincount = $user->logincount;
++$logincount;
$user->save();
//Redirect to the Intended Page
return Redirect::intended('/');
} else {
return Redirect::route('home')->with('global', 'Email or Password Incorrect or account not activated');
}
}
return Redirect::route('home')->with('global', 'There was a problem signing you in :(');
}
Upvotes: 0
Views: 667
Reputation: 219936
Use Eloquent's increment
method:
$user->increment('logincount');
Upvotes: 2
Reputation: 125
What you're doing here, is fetching the $user->logincount number from the database and putting it into a variable. You then increase the variable's value by one instead of the user's actual login count.
You should do something like this instead:
$user->logincount = $user->logincount + 1;
$user->save();
// or
$user->logincount++;
$user->save();
Upvotes: 0
Reputation: 3337
You are using the local variable.
$logincount = $user->logincount;
++$logincount;
Should just be:
$user->logincount++
Upvotes: 0