Reputation: 87
I have created an API that records records on the LoginActivity table anytime a user logs in. I want to the recorded activity to be only recorded once in 24hrs for every user.
This is my activity_record.py model
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class ActivityRecord extends Model
{
protected $fillable = ['user_id','total_logins', 'is_active'];
public function user()
{
return $this->belongsTo(User::class);
}
}
This is my create_activity_record_table.py table
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateActivityRecordsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('activity_records', function (Blueprint $table) {
$table->bigIncrements('id');
$table->integer('user_id');
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->integer('total_logins')->default(0);
$table->integer('is_active')->nullable();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('activity_records');
}
}
This is the UserController.py
public function __construct()
{
$this->middleware('auth:user');
}
public function login(Request $request)
{
$request->validate(['email' => 'required', 'password' => 'required']);
$credentials = ['email' => $request->email, 'password' => $request->password];
if (!$token = auth('user')->attempt($credentials)) {
return response()->json(['success' => false, 'message' => 'Email or Password Is Incorrect'], 401);
}
$user = Auth::guard('user')->user();
if (!$this->UpdateTwentyFours($user)) {
// Work here
if(!$user->is_active){
$activity = ActivityRecord::updateOrCreate(['is_active'=> 0,'user_id'=> auth('user')->user()->id])->increment('total_logins', 0);
}else{
$activity_add = ActivityRecord::updateOrCreate(['is_active'=> 1, 'user_id'=> auth('user')->user()->id])->increment('total_logins', 1);
}
};
return response()->json([
'success' => true,
'auth' => $this->respondWithToken($token),
'user' => new UserResource(User::where(['email' => $request->email])->first()),
]);
}
protected function respondWithToken($token)
{
return [
'access_token' => $token,
'token_type' => 'bearer',
'expires_in' => auth()->factory()->getTTL() * 60
];
}
public function UpdateTwentyFours($user)
{
$user = Auth::guard('user')->user()->id;
$now = Carbon::now()->toDateTimeString();
$activityUpdatedAt = ActivityRecord::where('user_id', $user)->get('updated_at');
$activityAt = $activityUpdatedAt->implode('updated_at');
$diff_in_hours = Carbon::createFromFormat('Y-m-d H:i:s', $activityAt)->format('Y-m-d H:i:s');
$diff_in = new Carbon($diff_in_hours);
$length = $diff_in->diffInHours($now);
if($length > 24){
return false;
}
return true;
}
I keep getting this error anytime I try to use the code above to achieve my purpose
Carbon\Exceptions\InvalidFormatException: Trailing data in file C:\Users\Desktop\PROJECT\vendor\nesbot\carbon\src\Carbon\Traits\Creator.php on line 643
#0 C:\Users\Desktop\PROJECT\vendor\nesbot\carbon\src\Carbon\Traits\Creator.php(665): Carbon\Carbon::rawCreateFromFormat('Y-m-d H:i:s', '2021-04-05 13:1...', NULL)
#1 C:\Users\Desktop\PROJECT\app\Http\Controllers\UserController.php(67): Carbon\Carbon::createFromFormat('Y-m-d H:i:s', '2021-04-05 13:1...')
#2 C:\Users\Desktop\PROJECT\app\Http\Controllers\UserActivityController.php(35): App\Http\Controllers\UserController->UpdateTwentyFours(11)
#3 C:\Users\Desktop\PROJECT\vendor\laravel\framework\src\Illuminate\Routing\Controller.php(54): App\Http\Controllers\UserController->store(Object(Illuminate\Http\Request))
#4 C:\Users\Desktop\PROJECT\vendor\laravel\framework\src\Illuminate\Routing\ControllerDispatcher.php(45): Illuminate\Routing\Controller->callAction('login', Array)
#5 C:\Users\Desktop\PROJECT\vendor\laravel\framework\src\Illuminate\Routing\Route.php(239): Illuminate\Routing\ControllerDispatcher->dispatch(Object(Illuminate\Routing\Route), Object(App\Http\Controllers\UserController), 'login')
Where am I going wrong and is there another way to get the recorded activity to be only recorded once in 24hrs for every user?
Upvotes: 1
Views: 107
Reputation: 4992
I think this is the most clear way to implement update:
class UserController {
public function login(){
...
$this->updateActivityEvery24Hours();
...
}
public function updateActivityEvery24Hours()
{
// Runs given callback function if cache does not exists or 24*60 minutes (24hours) is past
cache()->remember('user_activity_update', 24 * 60, function(){
$user = Auth::guard('user')->user()->id;
ActivityRecord::updateOrCreate([
'is_active'=> !$user->is_active,
'user_id'=> $user->id
])->increment('total_logins', $user->is_active ? 1 : 0);
});
}
}
Upvotes: 1