Search code examples
phplaravellaravel-8laravel-livewirelaravel-jetstream

Laravel Auth::user()->id returns null on livewire form


I'm try to get Auth::user()->id as my form value. It can shows on the label but it return value null.

enter image description here

View :

<option value="{{ Auth::user()->id }}" data-keterangan="">{{ Auth::user()->id }}</option>

Http/Livewire :

        $this->validate([
            'customer_code'=>'required|string',
            'customer_name'=>'required|string',
            'phone_number'=>'required|string'
        ]);

        StokItem::updateOrCreate([
            'customer_code'=>$this->customer_code,
            'customer_name'=>$this->customer_name,
            'phone_number'=>$this->phone_number
        ]);

    

Model :

    protected $fillable = ['id','customer_code','customer_name','phone_number','produk_code','produk_name','produk_uom','qty','kode_kondisi_barang','jenis_kondisi_barang','remark','url_foto','status'];

Solution

  • You cannot do auth()->name(), you need to call the authenticated user by doing auth()->user() then after that get the column you have in your database eg auth()->user()->name

    (https://laravel.com/docs/8.x/helpers#method-auth)

    In your Livewire Component, you should do something like this

    public $id = '';
    public $name = '';     
    public $no_hp = '';
    
    public function mount()
    {
       $this->id = auth()->id();         
       $this->name = auth()->user()->name;         
       $this->no_hp = auth()->user()->no_hp;
    }