Call to undefined method AppUser::id() (View:

I have created Custom Helper File App/Helpers/Helper.php for common functions, and I am trying to get data from the Helper class that I have created at Helper.php. Everything is fine when I call it in the blade file it shows an error “BadMethodCallException Call to undefined method AppUser::id()”

Helper.php

<?php

use AppCart;
use IlluminateSupportFacadesAuth;

function totalCartItems()
{
    if (Auth::check()) {
        $user_id = Auth::user()->id();
        $totalCartItems = Cart::where('user_id', $user_id)->sum('quantity');
    } else {
        $session_id = Session::get('session_id');
        $totalCartItems = Cart::where('session_id', $session_id)->sum('quantity');
    }
    return $totalCartItems;
}

Getting value at cart.blade

<div class="breadcrumbs">
  <ol class="breadcrumb">
        <li><a href="#">Home</a></li>
        <li class="active">Shopping Cart ({{ totalCartItems() }} item)</li>
  </ol>
</div>

How to resolve it?

Answer

You should use:

Auth::user()->id

or

Auth::id()

instead.