auth()->check is false
Hi,
I have a simple Trait in my Filament V3 app.
auth()->ckeck is false, but why? Any idea?
12 Replies
Where are you using this trait? It probably runs before any Middleware, so there is not authenticated user yet
I am using it the default Laravel User Model.
Yeah and the user model is booted before any middleware
hmmm.. Okay. Then I have to try this solution:
https://filamentphp.com/docs/3.x/panels/tenancy#simple-one-to-many-tenancy
I thought it would be better and more flexible in a Trait than directly in the model
middleware auth should be booted before user
Why do you need the
auth()->check()
outside of the Closures at all?
Move it to the closures if you need it and everything should be fine.
Very unlikely πThat was just my example. Here is the code and it is inside the closure but still false
public static function bootBelongsToTeam()
{
if (auth()->check()) {
static::creating(function ($model) {
$model->team_id = auth()->user()->team->id;
});
static::addGlobalScope('team_id', function (Builder $builder) {
return $builder->where('team_id', auth()->user()->team->id);
});
}
}
Line 3:
if (auth()->check()) {
it's not inside the closure. It's the first statement in a boot()
method.Ok, I will have a look at it.
In the docs
https://filamentphp.com/docs/3.x/panels/tenancy#simple-one-to-many-tenancy
It it also outside the closure
use Illuminate\Database\Eloquent\Builder;
class Post extends Model
{
protected static function booted(): void
{
if (auth()->check()) {
static::addGlobalScope('team', function (Builder $query) {
$query->where('team_id', auth()->user()->team_id);
// or with a
team
relationship defined:
$query->whereBelongsTo(auth()->user()->team);
});
}
}
}Hm. Not sure if that's right.
Maybe the problem is that I add the trait to the user model and the traits tries to fetch the authenticated user but for this it needs to boot the user model and thats an loop...
Hmm... In my other plain laravel 10 app without Filament it works without any problem