Undefined Variable in View Laravel 5.6 - php

i try to solve this problem and read many post but nothing help me, try to figure out my problem, as i am new to laravel!
this is my Index.blade.view located in view/posts
<!DOCTYPE html>
<html>
<head>
<title>Post</title>
</head>
<body>
<ul>
<?php
foreach ($posts as $post) {
echo "<li><a href = 'post/$post->$id'>".$post->$title."</a></li>";
}
?>
</ul>
</body>
</html>
PostController :
<?php
namespace App\Http\Controllers;
use App\Post;
use Illuminate\Http\Request;
class PostController extends Controller
{
public function index(){
$posts = Post::all();
return view('posts.index',compact($posts));
}
public function showPost($id){
$post = Post::find($id);
return view('posts.post',compact($post));
}
}
i read many post related to this but nothing help me, what i am doing wrong?
this is the problem i am facing : Undefined variable: posts (View: C:\xampp\htdocs\firstApplication\resources\views\posts\index.blade.php)

Let's assume you have another variable holding data, then your index method should look like:
Access content of $post as $post->id instead of $post->$id
public function index(){
$posts = Post::all();
$someData = []; // extra variable
return view('posts.index',compact('posts','someData'));
}
Another Change to be made is in view file:
On a side note: you don't have to use traditional PHP tags and foreach, instead you could use Laravel's clean and elegant method like following:
Replace your block of code:
<?php
foreach ($posts as $post) {
echo "<li><a href = 'post/$post->$id'>".$post->$title."</a></li>";
}
?>
Updated code:
#foreach($posts as $post)
<li><a href = "{{ url('post/'. $post->id) }}" </a></li>
#endforeach

Change view to
</head>
<body>
<ul>
<?php
foreach ($posts as $post) {
echo "<li><a href = 'post/$post->id'>".$post->title."</a></li>";
}
?>
</ul>
</body>
</html>
Change $post->$id to $post->id and $post->$title to $post->title
Also compact($posts) to compact('posts') and compact($post) to compact('post')

Related

Call to undefined method App\User::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 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)

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

Access Element of a field Variable

I want to access an element of a variable sent to the view
Here is my Controller
public function more($id)
{
$chickdata = Gamefarm::where('id','=',$id)->get();
$photos = Photo::where('chicken_id','=',$id)->get();
return View::make('gamefarms/readmore',compact('chickdata','photos'));
}
I am sending the variable 'photo' to the views
Here is the code that i want to work on views
#foreach ($photos as $myphotos)
#endforeach
<?php dd($myphotos->photo_loc[3]); ?>
I would try something like this:
public function more($id){
$chickdata = Gamefarm::where('id','=',$id)->get();
$photos = Photo::where('chicken_id','=',$id)->get();
$viewdata = array(
'chickdata'=> $chickdata,
'photos'=> $photos
);
return View::make('gamefarms/readmore', $viewdata);
}
Your view code is incorrect. It should be this.
#foreach ($photos as $myphotos)
{{ $myphotos->photo_loc[3] }}
#endforeach
No need to change your controller code - it is correct

CakePHP and conditions

So in my controller MenuController.php I have the following code:
class MenuController extends AppController {
public $helpers = array('Html', 'Form');
public function index() {
$this->set('menus', $this->Menu->find('all'));
$userSpecific = $this->Menu->find('all', array(
'conditions' => array('Menu.user_id' => '20')
));
}
}
and in my view, I am doing the following:
<?php foreach ($menus as $menu): ?>
<?php echo $menu['Menu']['id']; ?>
<?php echo $menu['Menu']['user_id']; ?>
<?php endforeach; ?>
update
To better understand this in my browser I changed my view to the following:
<?php foreach ($menus as $menu): ?>
<p>Menu id <?php echo $menu['Menu']['id']; ?> is for user: <?php echo $menu['Menu']['user_id']; ?></p>
<?php endforeach; ?>
end update
Now in the view, it is currently using the $this and returning all values from the database table, How do I change the view to use $userSpecific rather than $this I managed to get this far (making the $userSpecific part) by using the cookbook but I could only find the controller side and not the view side. I'm sorry if it's a bad question, just trying to learn.
You need to send the data to the view from the controller at the end of the index() function.
You can do it like this:
$this->set('userSpecific', $userSpecific);
or like this (my preferred way)
$this->set(compact('userSpecific');
Once you've done this, you can then modify your view to show the user specific fields as shown:
<?php foreach ($userSpecific as $menu): ?>
<?php echo $menu['Menu']['id']; ?>
<?php echo $menu['Menu']['user_id']; ?>
<?php endforeach; ?>

FuelPHP basics, using Model result in View

I am a little confused using fuelPHP 1.7.
The controller
class Controller_Website extends Controller
{
public function action_index()
{
// http://fuelphp.com/docs/general/views.html
$data = Website::get_results();
//var_dump($data) // (data is found here);
$views = array();
$views['head'] = View::forge('common/head', $data);
$views['header'] = View::forge('common/header', $data);
$views['sidebar'] = View::forge('common/sidebar', $data);
$views['content'] = View::forge('common/content', $data);
$views['footer'] = View::forge('common/footer', $data);
// return the rendered HTML to the Request
return View::forge('website', $views)->render();
}
}
The model
class Website extends \Model
{
public static function get_results()
{
// Database interactions
$result = DB::select('menu', 'url', 'title', 'text')
->from('aaa_website')
->where('id', '=', 1035)
->and_where('visible', '1')
->execute();
return $result;
}
}
All well sofar. Data is queried and found in the controller. What I am trying to accomplish is to use the data in my:
(nested) view
<html>
<head>
<?php echo $head; ?>
</head>
<body>
<header>
<div class="container">
<?php echo $header; ?>
</div>
</header>
<div class="row">
<div class="container">
<div class="col-md-4">
<?php echo $sidebar; ?>
</div>
<div class="col-md-8">
<?php echo $content; ?>
</div>
</div>
</div>
<footer>
<div class="container">
<?php echo $footer; ?>
</div>
</footer>
</body>
</html>
Head view (nested):
<title><?php echo $title; ?></title>
Content view (nested):
<h1><?php echo $title; ?></h1>
<div class="welcome_user"><?php echo $text; ?></div>
And so on.
The variables in the view in this example are not available because they are not explicitly set in the controller. Do they have to be set explicitly or is passing the data object also possible? If so, how do I access this objects data in the right way? FuelPHP is lacking good examples here and I am stuck now.
How do I do it?
The view data is converted from array indexed to view variable named. So:
View::forge('something', array('param' => 'value'));
Will correspond to the following view:
<h1><?=$param?></h1>
Where things are going wrong is is that you pass the plain DB result to the view. You'd need to get the first result from the database result, like this:
class Website extends \Model
{
public static function get_results()
{
// Database interactions
$result = DB::select('menu', 'url', 'title', 'text')
->from('aaa_website')
->where('id', '=', 1035)
->and_where('visible', '1')
->as_assoc()
->execute()
->to_array();
return reset($result);
}
}
Note that I've first used ->to_array() to convert the result object to an array, then reset() to get the first result. I've also added ->as_assoc() to make sure you get an array result, ->as_object() would give you a stdClass instance.

Categories