Rob
Rob

Reputation: 7101

Laravel - Access The Authenticated User In A Model Observer

I followed the documentation for creating a model observer here https://laravel.com/docs/5.5/eloquent#observers.

But when I try and access the authenticated user I get null.

How can I access the authenticated user in the model observer?

<?php

namespace App\Observers;

use App\Customer;

class CustomerObserver
{
    public function created(Customer $customer)
    {
        dd(auth()->user());
    }

    public function updated(Customer $customer)
    {
        dd(auth()->user());
    }
}

I've also tried this inside the Customer model and it returns null as well.

public static function boot()
{
    parent::boot();

    self::updated(function ($model) {
        dd(auth()->user());
    });
}

Upvotes: 1

Views: 3654

Answers (1)

Rob
Rob

Reputation: 7101

Ok, so stupid mistake on my end.

Thanks @fubar for the tip.

I was using a custom authentication provider so I needed to do this:

dd(auth()->guard('admin')->user());

Upvotes: 1

Related Questions