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?
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
You should use:
Auth::user()->id
or
Auth::id()
instead.
Method 2
Instead of doing this
Auth::check()
Use this
if(Auth::user() !== null)
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0