Laravel Undifined Variable in View - php

I cant't figure out what's going wrong with a link from my "welcome" page to a "profile" page.
It says "Undefined variable: restaurants (View: /Users/beyerdynamic/Documents/Developer/dev1/resources/views/welcome.blade.php)"
The strange thong is that I pass the Variable to my view.
My PagesController is:
public function welcome() {
$restaurants = User::orderByRaw('RAND()')->take(3)->get();
return view('welcome')->withRestaurants($restaurants);
}
My View is:
#foreach($restaurants as $key => $restaurant)
<div class="col-md-4">
<div class="card">
<div class="image">
<img src="{{asset('images/frontend/profile/dummy/profilehero/hero4.png')}}" alt="..." />
<div class="filter filter-white">
<a href="{{ URL::to('profile/'.$restaurant->id)}}" type="button" class="btn btn-info btn-round btn-fill">
<i class="fa fa-heart"></i> View Restaurant
</a>
</div>
</div>
</div>
</div>
#endforeach
The Restaurants Variable is passed properly to my welcome view, but when I click the link the error occurs on /profile/{id} url.

Change return view('welcome')->withRestaurants($restaurants);
to
return view('welcome')->with('restaurants', $restaurants);
OR
return view('welcome', compact('restaurants');

Try with this,
return view('welcome')->with("restaurants",$restaurants);
OR
return view('welcome',["restaurants" => $restaurants]);
Check laravel docs : https://laravel.com/docs/master/views#passing-data-to-views

Change the following line:
return view('welcome')->withRestaurants($restaurants); // there is nothing like withRestaurants in laravel
to
return view('welcome', array('restaurants' => $restaurants));
and try again.

Related

Undefined Route

I am very new to laravel and I am really terrible with routing. I want to delete the specific data but it say that route is undefined
CandidateController.php
this is my method to delete
public function destroy(Form $candidates)
{
$candidates->delete();
return redirect()->route('candidate.approve');
}
route
Route::resource('candidates', CandidateController::class);
I am using a resourse, when I go through the tutorial, it shortened my code into above. When I clicked the button delete, it says that Undefined route [candidate.approve]. Can someone help me where I went wrong?
blade
#foreach ($candidates as $candidate)
<div class="modal__content">
<div class="p-5 text-center"> <i data-feather="x-circle" class="w-16 h-16 text-theme-6 mx-auto mt-3"></i>
<form action="{{ route('candidates.destroy', $candidate->id) }}" method="POST">
#csrf
#method('DELETE')
<div class="text-3xl mt-5">Are you sure?</div>
<div class="text-gray-600 mt-2">Do you really want to delete these records? This process cannot be undone.</div>
<button type="button" data-dismiss="modal" class="button w-24 border text-gray-700 dark:border-dark-5 dark:text-gray-300 mr-1">Cancel</button>
<button type="submit" title="delete" class="button w-24 bg-theme-6 text-white" >Delete</button>
</div>
<div class="px-5 pb-8 text-center">
</div>
</div>
</form>
</div>
#endforeach
web.php
Route::get('application/approve/{id}', 'CandidateController#postApprove')->name('application');
Route::get('candidate', [CandidateController::class, 'approve'])->name('candidate.approve');
Route::resource('candidates', CandidateController::class);
Just add new Route with candidate.approve name before Route::resource.
your web.php file will be like this
Route::get('your-url', [CandidateController::class, 'approve')->name('candidate.approve');
Route::resource('candidates', CandidateController::class);
But its better to use prural for named route, like the resource controller :
candidates.create
candidates.store
...
UPDATE
Since i know the flow of the app, you should use this on controller:
return back();
Why? because when admin click Delete on modal, it will goes to another URL to delete data from DB. After delete, return back() will redirect admin to previous URL

Cannot find the way to make #if statement works in blade

I'm making a "teacher's" app, and I want to make a log-in page which changes depending if there's registered users in the database or not.
I want to make a redirection button to a create user page if there aren't auth users in database, and to make a select user view if the database have one or more users.
The problem is that I don't know how to exactly do this, 'cause the view always shows me the first statement (what I've got in the if), also if in the database are registered users. Can anyone help me with this please?
This is the blade file:
#if (empty(Auth::user()->id))
<div class="grid-item" id="grid-item5">
<div id="title">
<h1>Welcome</h1>
<p>We see there aren't users</p>
</div>
<div id="loginForm">
<button type="button" onclick="window.location='{{ url("/newUser") }}'">Button</button>
</div>
</div>
#else
<div class="grid-item" id="grid-item5">
<div id="title">
<h1>Select an user</h1>
</div>
<div id="loginForm"></div>
</div>
#endif
Here you have the controller index method:
public function index()
{
$users = User::all();
return view('/', compact('users'));
}
And finally here you have the page:
The following code is the sample for it, kindly replace code accordingly
#if(!$user)
//show button
#else
//dont show button
#endif
I think your question is you want to check if there is user in database.
So no need to check if the user authenticated but to check if there is user on the database.
In your controller
public function index() {
return view('/', ['users' => User::all()]);
}
and in your blade file
#if(!$users)
<div class="grid-item" id="grid-item5">
<div id="title">
<h1>Welcome</h1>
<p>We see there aren't users</p>
</div>
<div id="loginForm">
<button type="button" onclick="window.location='{{ url("/newUser") }}'">Button</button>
</div>
</div>
#else
<div class="grid-item" id="grid-item5">
<div id="title">
<h1>Select an user</h1>
</div>
<div id="loginForm"></div>
</div>
#endif
This function will get the current authenticated user: Auth::user(). I guess what you are trying to achieve is #if(empty($users)) where $users is the variable you are passing on controller.
If you want to verify if the user that accessed to that view is authenticated you can simply use #auth and #guest.
Also i would suggest you to change your button to an <a> tag and your href would be <a href="{{ route('route.name') }}" where route.name would be defined in your routes file.
in your controller:
you can create a folder inside views called users and then the index.blade.php (views/users/index.blade.php)
public function index()
{
$users = Users::all();
return view('users.index')->with('users', $users);
}
in your view:
#if(count($users) < 1)
...
#else
...
#endif
count is validating if the $users array length is less then 1 (in other words if the array is empty).
Alternative you can you isEmpty()
#if($users->isEmpty())
...
#else
...
#endif

How can I fix undefined variable problem?

My $links and $sliderimages variables work great. The $klas variable has been made by the same way like the first two I said, and for some reason it says that it is undefined variable.
First $klas was meant for another view, however I decided to test it out on my home page view where the other 2 variables were working were, but when i have put the $klas the same error occurs.
Route::get('/', function () {
$sliderimages = App\Sliderimage::all();
$links = App\Link::all();
$klas = App\Kla::all();
return view('home', compact('sliderimages'), compact('links'), compact('klas'));
});
That is on web.php file
#foreach($links as $link)
<div class="col-lg-4">
<img src="{{ Voyager::image( $link->image ) }}" class="rounded-circle" width="140" height="140" style="margin-left:25%">
<h2>"{{$link->title}}"</h2>
<p>"{{$link->text}}"</p>
<p><a class="btn btn-secondary" href="{{$link->slug}}" role="button">За повече информация. »</a></p>
</div>
#endforeach
</div>
#foreach($klas as $kla)
<p>"{{$kla->klastitle}}"</p>
#endforeach
That is on home.blade . php
The error is:
Undefined variable: klas (View: D:\xampp\htdocs\koko\diplomnata\resources\views\home.blade.php)
Change this:
return view('home', compact('sliderimages'), compact('links'), compact('klas'));
To this:
return view('home', compact('sliderimages', 'links', 'klas'));
Or for more longer but IMO more readable syntax:
return view('home')
->with('sliderimages', $sliderImages)
->with('links', $links)
->with('klas', $klas);
https://laravel.com/docs/master/views#passing-data-to-views

Trying to get property of non-object error in laravel 5.4

I'm trying register in my app but this Error happened and I don't know why.
and my post.blade.php file has this code:
<div class="blog-post">
<h2 class="blog-post-title">
<a href="/posts/{{$post->id}}">
{{$post->title}}
</a>
</h2>
<p class="blog-post-meta">
{{$post->user->name }}
{{$post->created_at->toFormattedDateString()}}
</p>
{{$post->body}}
postcontroller has this code:
public function index()
{
$posts=Post::latest()->get();
return view('posts.index',compact('posts'));
}
and index file is:
#foreach($posts as $post)
#include('posts.post')
#endforeach
<nav class="blog-pagination">
<a class="btn btn-outline-primary" href="#">Older</a>
<a class="btn btn-outline-secondary disabled" href="#">Newer</a>
</nav>
</div><!-- /.blog-main -->
I think your code need to update like:
public function index()
{
$posts=Post::with('users')->latest()->get();
return view('posts.index',compact('posts'));
}
<p class="blog-post-meta">
{{$post->users->name }}
{{$post->created_at->toFormattedDateString()}}
</p>
Hope this work for you!
assume that you are including post.blade.php in index.blade.php file.
In above case you are not passing $post to post.blade.php. Your foreach loop will be like :
#foreach($posts as $post)
#include('posts.post', ['post' => $post])
#endforeach
I assume that you are including post.blade.php in index.blade.php file.
In above case you are not passing $post to post.blade.php. Your foreach loop will be like :
#foreach($posts as $post)
#include('posts.post', ['post' => $post])
#endforeach

Laravel 5 times out when rendering any view with data passed from controller

In my application, I've always been able to pass data to any view as one would normally do using view('myView', compact('data'));. As of today, any view I try to render this way times out. I'm getting the error Maximum execution time of 120 seconds exceeded in Whoops!. I tried increasing php.ini and httpd.conf timeout times but no cigar. It's really odd and it doesn't make sense to me because I've always been able to render my views almost instantly, even when retrieving 15k+ records from the database and passing them to the view like I've always done.
My controller:
use App\Product;
use Illuminate\Support\Facades\Session;
class HomeController extends Controller {
public function __construct()
{
$this->middleware('auth');
}
public function index()
{
//the controller is normally like this
//$products = Product::paginate(16);
//return view('home', compact('products'));
//I'm testing with these 2 lines below but no cigar.
$product = Product::wherePid(303)->first();
return view('test', compact('product'));
}
}
The test view I created:
#extends('app')
#section('content')
{{ $product->name }}
#stop
My application view:
#extends('app')
<pre>{{ var_dump(Session::all())}}</pre>
#section('content')
<div class="row">
#foreach($products as $product)
<div class="col-xs-6 col-sm-3 col-lg-3 col-md-3">
<?php
if($product->img[7] == 'm' || $product->img[7] == 'M') echo "<div class='continenteIcon'></div>";
else echo "<div class='jumboIcon'></div>";
?>
<div class="thumbnail">
<a href="products/{{$product->pid}}"><img src="{{$product->img}}" title="
<?php
if($product->dispname != '') echo $product->dispname;
else echo $product->name;
?> ">
</a>
<div class="caption">
<h4>
<a style="text-decoration:none;" class="wordwrap" title="
<?php
if($product->dispname != '')
echo $product->dispname;
else echo $product->name;
?>" href="products/{{$product->pid}}">
<?php
if($product->dispname != '')
echo $product->dispname;
else echo $product->name;?>
</a>
</h4>
<p>{{$product->brand}}</p>
<span class="pull-right price">€{{$product->price}}</span>
<br/>
<span class="pull-right ppk">€{{round($product->pricekilo, 2)}} Kg, L ou Und</span>
</div>
<div class="ratings">
<p class="pull-right"> {{-- # review--}}</p>
<p>
<form method="post" action="add/{{$product->pid}}">
<input type="hidden" name="_token" value="{{{ csrf_token() }}}" />
<button title="Adicionar ao carrinho" type="submit" class="btn btn-success">
<i class="fa fa-shopping-cart"></i>
</button>
</form>
<form method="post" action="products/related/{{$product->pid}}">
<input type="hidden" name="_token" value="{{{ csrf_token() }}}" />
<button title="Ver artigos semelhantes" style="position:relative; bottom:35px;" type="submit" class="btn btn-info pull-right">
<i class="fa fa-search"></i>
</button>
</form>
</p>
</div>
</div>
</div>
#endforeach
</div>
<div class="row">
{!! $products->render() !!}
</div>
<div class="row">
<div class="pull-right">
* Preço por unidade, Litro ou Kilograma
</div>
#stop
#section('scripts')
#stop
The problem doesn't only happen in this view, but every single time I try to fecth someting from the database and pass it to the view to render. I keep getting timeouts and I can't seem to fix it no matter what I do.
I am clueless why this is happening. It seems like it started out of the blue. I have no Idea what could be causing this issue.
Any help?
P.S.: I'm using Wamp.
EDIT: I forgot to add something that might be important:
Everything is up and running in Wamp. If I dd() out the query result and do not render the view
$products = Product::paginate(16);
dd($products);
//return view('home', compact('products'));
this is fast, as it always used to be. And by fast I mean it takes less than 1 second to retrieve everything I need. But if I render the view with
return view('home', compact('products'));
everything just stalls and I get a 500 (I checked with Fiddler2 and after the page stops loading, the request status is 500)
It seems like you may be requesting too many records which may be using too much of your RAM. I would use the chunk command to help you with managing the amount you're requesting.
For example:
User::chunk(200, function($users)
{
foreach ($users as $user)
{
//
}
});
First check logs.
Next try to dd($product)
Next if you try to render view with last 2 lines (getting first record) remove pagination from template.
Clean template to minimum e.g.
#extends('app')
#section('content')
<div class="row">
#foreach($products as $product)
#endforeach
</div>
#stop
I just sorted it out. The issue was in the following block of code in app.blade.php.
$size = Session::get('size');
...
<input type="text" value="'.Session::get($item).'">
...
I was messing around with data from an existing session and everything was working fine. I assumed I was doing it right. I wasn't. Not by a chance :)
Assumption is the mother of all screw ups.
Surrounded the whole block with if(Session::has('size') and everything is blazing fast and running smoothly as usual.
Thanks #Pyton for pointing me out into the right direction and thanks everyone for your contribution.

Categories