ErrorException Undefined variable: - php

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

Related

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?

Why can't I have two separate functions returning two different views simultaneously?

I'm playing around with Laravel but I'm having an issue with the controller returning views. $aboutUs works but for $footerText I get an error that says:
Undefined variable: footerText (View:
/Users/user/sublime/blog/resources/views/about-
us.blade.php)
What am I doing wrong and how can I fix it?
Here's AboutUsController.php:
<?php
namespace App\Http\Controllers;
class AboutUsController extends Controller
{
public function index()
{
$aboutUs = "About Us";
return view('about-us', compact("aboutUs"));
}
public function indexTwo()
{
$footerText = "Some more text here";
return view('footer-content', compact("footerText"));
}
}
Here's views/about-us.bladephp:
#extends('layouts.about-us')
#section('title', $aboutUs)
#section('about-content')
<div class="container">
<h1>{{ $aboutUs }}</h1> {{-- This works --}}
<h1>{{ $footerText }}</h1> {{-- This doesn't work --}}
</div>
#endsection
In returning 2 things in a single function, try this using with.
public function index()
{
$aboutUs = "About Us";
$footerText = "Some more text here";
return view('about-us', compact("aboutUs"))
->with('footer-content', compact("footerText"));
}

Faced the error when wanted to create pagination in Laravel

I wanted to create pagination in index page and as I read in Laravel documentation it is possible to use paginate method with orderBy method when I do that I faced error:"Method Illuminate\Database\Eloquent\Collection::orderBy does not exist.". The code I am using:
public function index()
{
$user_id=auth()->user()->id;
$user=User::find($user_id);
$personal=$user->personalAccounting->orderBy('asc')->paginate(2);
$balance=$user->balance;
return view('personal.index', compact('personal','balance'));
}
#extends('layouts.app')
#section('content')
<h1>Домашняя Бухгалтерия</h1>
<br>
#if($balance==0)
<h2 class="text-center">Ваш Баланс: <span class="badge badge-primary">0.00</span></h2>
#elseif($balance<0)
<h3 class="text-center">Ваш Баланс: <span class="badge badge-danger">{{$balance}}</span></h3>
#else
<h3 class="text-center">Ваш Баланс: <span class="badge badge-success">+{{$balance}}</span></h3>
#endif
<br>
Создать
<br>
#if(count($personal)>0)
#foreach($personal as $pers)
<br>
<div class="card">
<h2><a href="/personal/{{$pers->id}}" >{{$pers->TypeOfAccounting}}</a></h2>
<h5 class="">Наименование:<span class="badge">{{$pers->Name}}</span></h5>
</div>
#endforeach
{{$personal->links()}}
#else
<p>Не найдено записей</p>
#endif
#stop
public function index()
{
$user = auth()->user(); // It's already the user model
$personal = $user->personalAccounting()->orderBy('YOUR_COLUMN')->paginate(2);
$balance = $user->balance;
return view('personal.index', compact('personal','balance'));
}
Notice personalAccounting() instead of personalAccounting The reason is, when you call the attribute without (), Laravel will load all the data from your DB in a collection. Every modification you do after, will be done with PHP.
When you request with the method using (), you're modifying the QueryBuilder which mean the orderBy and the pagination will be executed by MySQL which will also increase the performance and reduce the memory usage.
Give a column name before asc
public function index()
{
$user_id=auth()->user()->id;
$user=User::find($user_id);
$personal=$user->personalAccounting->orderBy('**your_column_name**','asc')->paginate(2);
$balance=$user->balance;
return view('personal.index', compact('personal','balance'));
}
Try to use latest().
public function index()
{
$user_id=auth()->user()->id;
$user=User::find($user_id);
$personal=$user->personalAccounting->latest('***Add column name***')->paginate(2);
$balance=$user->balance;
return view('personal.index', compact('personal','balance'));
}

CRUD error in Laravel

Hello guys I made a CRUD(just create and read ) in Laravel project ,the create is working good and i passed the "loan" in show function but in the view it says undefined variable:
my show function in controller:
public function show($id)
{
$loan=loan::find($id);
return view('finance/loans')->with('loan',$loan);
}
My routes:
Auth::routes();
Route::get('/loans', 'LoanController#viewLoanForm');
Route::post('/loans', 'LoanController#store');
Route::get('/home', 'HomeController#index')->name('home');
Route::resource('loan','loanController');
Route::get('finance/loans', function () {
return view('loans');
});
And here is where i call the variable loan in the view:
#extends('layouts.app')
#section('content')
<link href="{{ asset('css/loans.css') }}" rel="stylesheet">
<html>
<div class="container">
...
</div>
</div>
</div>
<div class="row">
<h1>{{$loan->nume}}</h1>//"nume"is the row from db i want to show
</div>
</div>
</html>
#endsection
The ERROR
You misspelled the route!
Your request does not reach the controller method
Route::get('finance/loans', function () {
return view('loans');
});
should be so
Route::get('finance/loans/{$id}','loanController#show');
or should use the controller resource route
Route::resource('loans','loanController');
url 'loans/show/{$loan_id}'
Show Loan
your return should be like this:
return view('finance/loans')->with(['loan'=>$loan]);
instead of
return view('finance/loans')->with('loan',$loan);
I think you need to on the route::resource('finance/loans') instead of ('loans').
And will work for sure
Use this :
return view('finance.loans',compact(['loan']));

#include a view with controller functionality - Laravel 5.4

I am working on a profile page for my web application. Within this view profile.blade.php I would like to include the view progress/index.blade.php. I have the following structure:
profile.blade.php
<div class="panel panel-default">
<div class="panel-heading clearfix">
<h1 class="panel-title pull-left">{{ $user->name }} Progress</h1>
</div>
<div class="panel-body">
#include('client.progress.index')
</div>
</div>
web.php
Route::group(['middleware' => ['auth', 'client'], 'prefix' => 'client', 'as' => 'client.'], function () {
Route::get('home', 'Client\HomeController#index')->name('home');
Route::get('profile', 'Client\UserController#profile')->name('profile');
Route::get('progress', 'Client\UserController#progress')->name('progress.index');
});
UserController#progress
public function progress(){
$auth = Auth::user();
$progressPictures = Picture::select('*')
->where('user_id', $auth->id)
->get();
return view('client.progress.index', ['progressPictures' => $progressPictures]);
}
client.progress.index
<p>Progress pictures</p>
#foreach($progressPictures as $progressPicture)
<img src="/storage/uploads/progress/{{ $progressPicture }}" style="width:150px; height:150px; float:left; border-radius:50%; margin-right:25px;">
#endforeach
When I remove the php part from the index.blade.php, the site works. but when i add the foreach loop, $progressPictures is undefined. I am not calling the UserController#progress in some way. Could some one help me with this?
Generally based on my observation, the variable is not making it to the views because you are routing to another while the other view is handled by another controller.
One of the ways you can do that is either to have a trait where you can easily reuse the result of getting progressPictures or because you quickly need it, you might have to duplicate this code as well in the profile method in your UserController so that you can have the progressPictures also in profile page:
So you'll have:
public function profile()
{
//codes before or after
$auth = Auth::user();
$progressPictures = Picture::select('*')
->where('user_id', $auth->id)
->get();
//......
return view('profile', compact('progressPictures'));
Ps: unnecessary code repetition is not generally recommended, but I would do this first then clean up things after.
Change this to
return view('client.progress.index', ['progressPictures' => $progressPictures]);
to this
return view('client.progress.index')-> with('progressPictures', $progressPictures);
Change
#include('client.progress.index')
to
#include('client.progress.index', ['progressPictures' => $progressPictures])

Categories