Call to undefined method App\User::id() (View: - php

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 App\User::id()"
Helper.php
<?php
use App\Cart;
use Illuminate\Support\Facades\Auth;
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>Home</li>
<li class="active">Shopping Cart ({{ totalCartItems() }} item)</li>
</ol>
</div>
How to resolve it?

You should use:
Auth::user()->id
or
Auth::id()
instead.

Instead of doing this
Auth::check()
Use this
if(Auth::user() !== null)

Related

ErrorException Undefined variable:

Why I am getting this error?
ErrorException
Undefined variable: features (View: C:\xampp\htdocs....views\layouts\index.blade.php)
FeaturedController.php
public function index()
{
$features = Feature::get();
return view ('layouts.index')->with(compact('features'));
}
ProductsController.php
public function index()
{
$products = Product::get();
return view ('products')->with(compact('products'));
}
layouts page- index.blade.php
#yield('content')
#foreach($features as $f)
<li>
<div class="prodcut-price mt-auto">
<div class="font-size-15">LKR {{ $f ['features_id'] }}.00</div>
</div>
</li>
#endforeach
view page - index.blade.php
#extends('layouts.index')
#section('content')
#foreach($products as $p)
<div class="mb-2">{{ $p ['prod_sub_category'] }}</div>
<h5 class="mb-1 product-item__title">{{ $p ['prod_name'] }}</h5>
<div class="mb-2">
<img class="img-fluid" src="{{asset('/storage/admin/'.$p ['prod_image_path'] ) }}" alt="Image Description">
</div>
<div class="flex-center-between mb-1">
<div class="prodcut-price">
<div class="atext">LKR {{ $p ['prod_price'] }}.00</div>
</div>
<div class="d-none d-xl-block prodcut-add-cart">
<i class="ec ec-shopping-bag"></i>
</div>
web.php
Route::resource('/products', 'ProductsController');
Route::resource('/layouts/index', 'FeaturedController#index');
Aside from not passing your variables to your blade views appropriately which other answers have pointed out, your trying to access features from a controller that does not have features set.
The controller below sets features and then makes use of it in the layouts.index blade file.
FeaturedController.php
public function index()
{
$features = Feature::get();
return view ('layouts.index')->with(['features' => $features]);
// or
// return view ('layouts.index', compact('features'));
}
While this controller sets products but then makes use of a blade file that extends another blade file that has a features variable in it. This is why your getting the error
ProductsController.php
public function index()
{
$products = Product::get();
return view ('products', compact('products'));
}
And to fix it you must pass the features variable along side products like so:
ProductsController.php
public function index()
{
$products = Product::get();
$features = Feature::get();
return view ('products')->with(['features' => $features, 'products' => $products]);
}
But if more than one blade file is going to extend this layouts.index file then this approach is not advisable, and situations like this is why Taylor Otwell introduced Blade Components. You can now move the features blade view and logic to a component that can wrap around any other file you want or be included.
The documentation is straight forward but if you want me to show you how to implement it to solve your dilemma then hit me up on the comment below.
as u r using data in layout u should use laravel view composer to share data to layout file ref link https://laravel.com/docs/7.x/views#view-composers
in your AppServiceProvider.php
inside boot() add this line
public function boot()
{
\View::composer('layouts.index', function ($view) { // here layout path u need to add
$features = Feature::get();
$view->with([
'features'=>$features,
]);
});
}
It share data based on specif view file like here layouts.index data is send to this view so if u not send data from controller it will get data from view composer
You can change your controller to this:
public function index()
{
$features = Feature::all();
return view ('layouts.index', compact('features'));
}
A your blade you should actually do #section instead:
#section('content')
#foreach($features as $f)
<li>
<div class="prodcut-price mt-auto">
<div class="font-size-15">LKR {{ $f->features_id }}.00</div>
</div>
</li>
#endforeach
#endsection

Call to undefined function App\Transaksi()

i have a problem with my coding, i want to count user on my database but it's appear to be like this
Symfony \ Component \ Debug \ Exception \ FatalThrowableError (E_ERROR)
Call to undefined function App\Transaksi()**
Here's my index.php
<div class="col-lg-4 col-xs-6">
<!-- small box -->
<div class="small-box bg-aqua">
<div class="inner">
<h3>{{ $list->transaksi }}</h3>
<p>Transaksi</p>
</div>
and my controller.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class BackController extends Controller
{
public function list()
{
$transaksi = \App\Transaksi::get();
$transaksi = \App\Transaksi('id')->count();
return view('/admin', compact('list'));
}
}
and my routes
Route::group(['prefix'=>'user','middleware' => ['auth', 'role:member']],
function (){
Route::get('/mybook','FrontController#mybook');
});
Route::group(['prefix'=>'admin','middleware' => ['auth', 'role:admin']], function(){
Route::get('/',function() {
return view('admin.index');
});
Route::get('/','BackController#list');
Route::get('logout','UserController#logout');
Thanks.
Sorry For the late reply main bug in your list function is
public function list()
{
$transaksi = \App\Transaksi::get();
$transaksi = \App\Transaksi('id')->count();
return view('/admin', compact('list'));
}
You are Using the Same varible name to
Retrive all the records $transaksi = \App\Transaksi::get(); and
also for the Counting all the records $transaksi = \App\Transaksi('id')->count();
and also you are not passing it to the balde viewer
instead You are passing the function name list
return view('/admin', compact('list'));
Solution To you problem
First you need not to write \App\Transaksi in every where
Just Go to the top of the controller and add this line
use App\Transaksi;
Then Your function
There are several ways to count the record
Method 1:
public function list()
{
$transaksi= Transaksi::latest()->paginate(10);
return view('transaksi.index', compact('transaksi'));
}
here view('transaksi.index') refers to
Projectname/resources/views/transaksi/index.blade.php
Then in your index.blade.php to get the count just use the code
<h3 class="modal-title">{{ $transaksi->total() }} {{ str_plural('Transaksi', $transaksi->count()) }} </h3>
Method 2:
public function list()
{
$transaksi = Transaksi::latest()->get();
$recordCount = Transaksi::count();
return view('transaksi.index', compact('transaksi','recordCount'));
}
Then in your blade file
<h3>{{ $recordCount }}</h3>
Hope it helps
Your controller isn't doing much right now. The view needs to be a valid blade template file, e.g. admin.index, not /admin. You then need to pass a variable into the view, not the function name.
public function list()
{
$transaksi = \App\Transaksi::all();
$numTransaksi = $transaksi->count();
return view('admin.index', compact('numTransaksi'));
}
Then in the view you can access the count via {{ $numTransaksi }}.
You also have two routes for / in your web.php. You should get rid of the first one if you want the BackController#list function to call properly.
Is this what you mean?

Laravel withErrors 5.4.36 is empty within view

Strange issue here! My return code within the controller is as follows:
return back()->withErrors([ 'not_updated' => 'Unable to update record or no changes made' ]);
And then I display the errors within blade:
#if ($errors->any())
<article class="message is-danger">
<div class="message-body">
<ul>
#foreach ($errors->all() as $error)
<li>{!! $error !!}</li>
#endforeach
</ul>
</div>
</article>
#endif
However this doesn't appear to be working at all, $errors is empty for some reason, however this works fine from another controller!
This is the method where this works, I have included the use classes.
namespace App\Http\Controllers;
use App\Pages;
use App\PlannerStatus;
use App\SubPages;
use App\VehicleMake;
use App\Website;
use App\WebsiteRedirects;
use Illuminate\Http\Request;
use Redirect;
class RedirectsController extends Controller
{
public function store(Request $request, Website $website)
{
$error = [ 'test' => 'test error' ];
if (!empty($error)) {
return back()->withErrors($error)->withInput();
}
return back();
}
}
And this is the controller where this does NOT work, as you can see they are the same, more or less!
namespace App\Http\Controllers;
use App\ResultsText;
use App\VehicleMake;
use App\VehicleModel;
use App\VehicleType;
use App\SearchPath;
use App\Website;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\MessageBag;
use Redirect;
class ResultsTextController extends Controller
{
public function update(Website $website, ResultsText $resultsText, Request $request)
{
$data = request()->except(['_token','id']);
$result = ResultsText::where('id', $resultsText->id)->update($data);
if (!$result) {
return back()->withErrors([ 'not_updated' => 'Unable to update record or no changes made' ]);
}
return Redirect::action('ResultsTextController#index', $website);
}
}
Also here are my Routes, just so you can see they are pretty much identical:
Route::prefix('/redirects')->group(function () {
Route::get('/', 'RedirectsController#index')->middleware('SettingStatus:redirect');
Route::patch('/update', 'RedirectsController#update');
});
Route::prefix('/results-text')->group(function () {
Route::post('{resultsText}/update', 'ResultsTextController#update');
});
Inside your blade try this
#if ($errors->any())
<article class="message is-danger">
<div class="message-body">
<ul>
#foreach ($errors as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
</article>
#endif
It's easily overlooked in your question. The problem is not what it seems. You will probably find it funny why it doesn't work.
Replace
return back()->withErrors([ 'not_updated' => 'Unable to update record or no changes made' ]);
with
return redirect()->back()->withErrors([ 'not_updated' => 'Unable to update record or no changes made' ]);

Controller Method not defined error - Laravel 5.1

I am trying to display the currently logged in username, as a link to the user info, in my main navigation. I can get the name to display, so I am pulling the info from the db, and passing it to the view OK. But, when I try to make it a link, I get the method not defined error.
Here is how I pass the user info to the navigation (as the var $userInfo):
public function index()
{
$Clients = \Auth::user()->clients()->get();
$userInfo = \Auth::user();
return view('clients.index', compact('Clients', 'userInfo'));
}
Here is the relevant bit from my navigation:
<ul class="nav navbar-nav">
<li>{!! link_to_action('AuthController#show', $userInfo->username, [$userInfo->id]) !!}</li>
</ul>
The method from my controller:
protected function show($id)
{
$userInfo = User::findOrFail($id);
return view('users.show', compact('userInfo'));
}
And, the route definition:
// User Display routes
Route::get('auth/{id}', 'Auth\AuthController#show');
Here is the error I get:
Action App\Http\Controllers\AuthController#show not defined.
Can anyone tell me what I am missing?
First, you need to make your AuthController::show() method public:
public function show($id)
{
$userInfo = User::findOrFail($id);
return view('users.show', compact('userInfo'));
}
Second, as your controllere is in App\Http\Controllers\Auth namespace, you need to use the **Auth** prefix in the view:
<ul class="nav navbar-nav">
<li>{!! link_to_action('Auth\AuthController#show', $userInfo->username, [$userInfo->id]) !!}</li>
</ul>

"Use of undefined constant..." error in Laravel

I am a Laravel newbie. I want to pass the results of a database query to a view. I get an error message "Use of undefined constant tasks - assumed 'tasks'". What am I doing wrong?
My code is as follows:
class TasksController extends BaseController{
public function index(){
$tasks = Task::all();
//return View::make(tasks.index, ['tasks' => $tasks]);
return View::make(tasks.index, compact('tasks'));
}
A snippet from my template page is shown below:
<body>
<h1>All tasks!</h1>
#foreach($tasks as $task)
<li>{{ $task-title }} </li>
#endforeach
return View::make('tasks.index')->with(compact('tasks'));
also change:
<li>{{ $task-title }} </li>
to
<li>{{ $task->title }} </li>
should be like this.
Try this,
return View::make(tasks.index, $tasks);
instead of
return View::make(tasks.index, compact('tasks'));

Categories