User visit behaviour for Laravel.
It used to record the number of visits to the model(documentation/subject/question).
Require Laravel Visit using Composer.
composer require laravel-interaction/visit
Publish configuration and migrations
php artisan vendor:publish --tag=visit-config
php artisan vendor:publish --tag=visit-migrations
Run database migrations.
php artisan migrate
use Illuminate\Database\Eloquent\Model;
use LaravelInteraction\Visit\Concerns\Visitor;
class User extends Model
{
use Visitor;
}
use Illuminate\Database\Eloquent\Model;
use LaravelInteraction\Visit\Concerns\Visitable;
class Subject extends Model
{
use Visitable;
}
use LaravelInteraction\Visit\Tests\Models\Subject;
/** @var \LaravelInteraction\Visit\Tests\Models\User $user */
/** @var \LaravelInteraction\Visit\Tests\Models\Subject $subject */
// Visit to Visitable
$user->visit($subject);
// Compare Visitable
$user->hasVisited($subject);
$user->hasNot
Visited($subject);
// Get visited info
$user->visitVisitors()->count();
// with type
$user->visitVisitors()->withType(Subject::class)->count();
// get visited subjects
Subject::query()->whereVisitedBy($user)->get();
// get subjects doesnt visited
Subject::query()->whereNotVisitedBy($user)->get();
use LaravelInteraction\Visit\Tests\Models\User;
use LaravelInteraction\Visit\Tests\Models\Subject;
/** @var \LaravelInteraction\Visit\Tests\Models\User $user */
/** @var \LaravelInteraction\Visit\Tests\Models\Subject $subject */
// Compare Visitor
$subject->isVisitedBy($user);
$subject->isNotVisitedBy($user);
// Get visitors info
$subject->visitors->each(function (User $user){
echo $user->getKey();
});
$subjects = Subject::query()->withVisitorsCount()->get();
$subjects->each(function (Subject $subject){
// like uv
echo $subject->visitors()->count(); // 1100
echo $subject->visitors_count; // "1100"
echo $subject->visitorsCount(); // 1100
echo $subject->visitorsCountForHumans(); // "1.1K"
// like pv
echo $subject->visitableVisits()->count(); // 1100
echo $subject->visits_count; // "1100"
echo $subject->visitsCount(); // 1100
echo $subject->visitsCountForHumans(); // "1.1K"
});
$subjects = Subject::query()->withVisitorsCount(function ($query){
return $query->whereKey(1);
})->get();
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use LaravelInteraction\Visit\Tests\Models\Subject;
use Illuminate\Http\Resources\Json\JsonResource;
class AuctionController extends Controller
{
public function show($id, Request $request){
$subject = Subject::query()->findOrFail($id);
dispatch(function () use ($subject, $request) {
$subject->record($request);
})->afterResponse();
return new JsonResource($subject);
}
}
Event | Fired |
---|---|
LaravelInteraction\Visit\Events\Visited |
When an object get visited. |
Laravel Eloquent Visit is an open-sourced software licensed under the MIT license.