The error you're encountering is due to the fact that the auth()->user() call returns null when running the seeder. This is because there is no authenticated user during the seeding process. To resolve this, you can modify the trait to check if there is an authenticated user before attempting to access the team_id.
Here's a revised version of your FilterByTeam trait:
<?php
namespace App\Traits;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Facades\Auth;
trait FilterByTeam
{
/**
* @property integer $team_id
*/
protected static function booted(): void
{
static::creating(function (Model $model) {
if ($user = Auth::user()) {
$model->team_id = $user->team_id;
}
});
// Define qualifyColumn to avoid ambiguous problems on relation queries
static::addGlobalScope('team', function (Builder $query) {
if ($user = Auth::user()) {
$query->where($query->qualifyColumn('team_id'), '=', $user->team_id);
}
});
}
}
Explanation:
-
Check for Authenticated User: Before accessing
auth()->user()->team_id, the code now checks if there is an authenticated user usingif ($user = Auth::user()). This prevents the error when there is no authenticated user, such as during seeding. -
Global Scope: The global scope is also wrapped in a check to ensure it only applies the filter if there is an authenticated user.
Seeding with a Specific Team ID:
Since the seeder does not have an authenticated user, you should explicitly set the team_id in your factory or seeder. Your PubFactory already sets a team_id, so it should work as expected.
Example Seeder:
If you need to seed with different team_id values, you can do something like this in your seeder:
<?php
namespace Database\Seeders;
use Illuminate\Database\Seeder;
use App\Models\Pub;
class PubSeeder extends Seeder
{
/**
* Run the database seeds.
*/
public function run(): void
{
// Seed pubs for team_id 1
Pub::factory()->count(10)->create(['team_id' => 1]);
// Seed pubs for team_id 2
Pub::factory()->count(10)->create(['team_id' => 2]);
}
}
This way, you ensure that the team_id is set correctly during the seeding process, and the trait will not throw an error due to the absence of an authenticated user.