Laravel route variable, foreach - php

I wan't to print all forums with foreach in laravel. I'm trying to write code:
Route::get('', function()
{
return View::make('home', array(
$forums = DB::table('select * from forums')
));
});
And then in template write foreach:
#foreach ($forums as $forum)
<p>This is forum {{ $forum->name }}</p><br>
#endforeach
But it's not working, it prints:
Undefined variable: forums (View: C:\myadmin\htdocs\resources\views\home.blade.php)
Thanks in advance !

The correct way of doing what you inted to do is the following :
Route::get('', function()
{
return View::make('home', array(
$forums = DB::table('forums')->select()->get()
));
});

Related

Undefined variable: names in Laravel 5.6 app?

I am going to count some table column values using following controller function,
public function showcategoryname()
{
$names = Vehicle::groupBy('categoryname')->select('id', 'categoryname', \DB::raw('COUNT(*) as cnt'))->get();
return view('_includes.nav.usermenu')->withNames($names);
}
then my route is,
Route::get('_includes.nav.usermenu', [
'uses' => 'VehicleController#showcategoryname',
'as' => '_includes.nav.usermenu',
]);
and my usermenu blade file is include with other blade files like this,
div class="col-md-3 ">
#include('_includes.nav.usermenu')
</div>
and usermenu blade view is,
#foreach($names as $name)
{{ $name->categoryname }} ({{ $name->cnt }})
#endforeach
in my url like this
http://localhost:8000/_includes.nav.usermenu
this is working fine. but when i visit other pages include usermenu blade it is generated following error,
Undefined variable: names (View: C:\Users\banda\Desktop\dddd\resources\views\_includes\nav\usermenu.blade.php) (View: C:\Users\banda\Desktop\dddd\resources\views\_includes\nav\usermenu.blade.php)
how can fix this problem?
it's clear that you are just using showcategoryname() method in _includes.nav.usermenu route not in every routes so it can't recognize that variable, it's better to use a global variable in all routes
so in app\Providers\AppServiceProviders.php in boot function use this code to have that variable in all routes:
view()->composer('*', function ($view) {
$names = Vehicle::groupBy('categoryname')->select('id', 'categoryname', \DB::raw('COUNT(*) as cnt'))->get();
$view->with('names', $names);
});
this code runs before any code or controller! actually is feature of boot function!
You can insert this code into boot function in App\Providers\AppServiceProvider class
public function boot(){
$names = Vehicle::groupBy('categoryname')->select('id', 'categoryname', \DB::raw('COUNT(*) as cnt'))->get();
View::share('names', $names);
}

laravel pagination : Call to a member function render() on array

In laravel controller I have following code:
public function getAdmins(){
//$users = $this->user->all();
$search[] =array();
$search['name']= Input::get('name','');
$search['uname']= Input::get('uname','');
$search['role']= Input::get('role','');
$users = $this->user->findUsers($search);
$exceptSuperadmin = array();
foreach($users as $user){
if(!$user->isUser())
$staffs[] = $user;
}
$users = #$staffs;
return view('users::admins.list')->with('staffs',$users)->with('search',$search);
}
In Model I have:
public function findUsers($search)
{
return self::where('name','like','%'.$search['name'].'%')
->where('username','like','%'.$search['uname'].'%')
->where('role','like','%'.$search['role'].'%')
->paginate(5);
}
And In blade file I have:
#if($staffs)
#foreach($staffs as $staff)
<!-- Some code here to loop array -->
#endforeach
#else
No Staffs
#endif
{!! $staffs->render() !!} Error comes at this line
I am not geeting why this error comes....staffs is an array and render() a function to echo the pagination pages...but can't getting the error...Anybody to help.
By applying foreach the pager object and assign an array you lose the paging properties, so you will have an array rather than a pager object.
I recommend the following solution for your case:
Controller:
public function getAdmins(){
$search[] =array();
$search['name']= Input::get('name','');
$search['uname']= Input::get('uname','');
$search['role']= Input::get('role','');
$users = $this->user->findUsers($search);
return view('users::admins.list')->with('users',$users)->with('search',$search);
}
Blade file:
#if($users)
#foreach($users as $user)
#if(!$user->isUser())
<!-- Some code here to loop array -->
#endif
#endforeach
#else
No Staffs
#endif
{!! $users->render() !!}
NO, render() doesn't work on an object per se, neither on the array you are creating out of the required object for the pagination to work (LengthAwarePaginator)
Since you have a collection, and you need one, you could use one of the methods provided to do your filtering, such as filter.
Something like (untested but should work):
$staff = $users->filter(function ($value, $key) {
return !$value->isUser();
});

Why my blade have Undefined Variable - Laravel 4.2

This is on my routes.php
Route::get('registration/verify/{confirmation}', ['as'=>'verify', 'uses'=>'HomeController#verify']);
Route::get('login', ['as'=>'login', 'uses'=>'HomeController#getLogin']);
and on my blade is this
then on my HomeController.php where the error belong
public function verify($confirmation)
{
$user = User::where('activation_code', '=', $confirmation)->first();
return Redirect::route('login')
->withInput(['email' => $user->email])
->with('fuck', 'wtf');
}
and I got error like this
Undefined variable: fuck (View: C:\Program Files (x86)\Ampps\www\tridg\local\app\views\auth\login.blade.php)
I don't know where I been wrong, I'm so confident that this is correct.
EDIT1:
I even tried this
public function verify($confirmation)
{
$user = User::where('activation_code', '=', $confirmation)->first();
// $user->active = 1;
// $user->save();
return Redirect::route('login', ['fuck'=>'wtf'])
->withInput(['email' => $user->email]);
}
Nevermind, The answer is {{ Session::get('var_name') }} not {{ $var_name }}

Laravel 4 Pagination not working (ErrorException)

I've searched for all solutions to implement pagination successfully, but nothing I've found worked. I'm new to Laravel so I have maybe only one of those basic misunderstandings.
I have created it like it is described in the current documentation. And I get the first page successfully, exactly the content i need, but when i try to use the pagination, clicking on the "next"-arrow, I get an error message:
ErrorException
Undefined variable: reviews (View: D:\Xampp\htdocs\laravel\app\views\search.blade.php)
I know what this generally means but absolutely no idea how to solve this.
This is the form in the view file:
{{ Form::open(array('url' => '/search', 'class' => 'search', 'method' =>'GET')) }}
{{ Form::text('title') }}
{{ Form::submit('Suche')}}
{{ Form::close() }}
Here is my routes configuration:
Route::any('/search', array('uses' => 'HomeController#search'));
Here is my function in the HomeController:
public function search() {
$input = Input::get('title');
if($input && $input != ''){
$games = DB::table('games')->where('name', 'LIKE', "%$input%")->get();
foreach ($games as $game) {
$reviews = DB::table('reviews')->whereGame_id($game->id)->paginate(3);
}
}
return View::make('search', compact('reviews', 'input', 'games'));
}
Here is the view-code of the search.blade.php view, which displays the results:
#section('content')
<h2>Suchergebnisse</h2>
#foreach ($reviews as $review)
#foreach ($games as $game)
#if ($game->id == $review->game_id)
<h3> {{ $game->name }} </h3>
#endif
#endforeach
<p>{{ (preg_replace('/\n/i', '<br/>', $review->body)) }}</p>
#endforeach
{{ $reviews->appends(array('term' => $input))->links() }}
#stop
I thank you beforehand if someone knows why Laravel has a problem with this solution.
Edit:
I've changed the compact-statement and replaced it with an simple array, just like that:
return View::make('search', array('reviews' => $reviews, 'input' => $input, 'games' => $games));
Then I've added global $games; global $reviews; to the Controller, so the Error "Undefined variable: reviews" disappeared. Now I've got the following message, but only on page 2, page 1 works fine:
ErrorException
Invalid argument supplied for foreach() (View: D:\Xampp\htdocs\laravel\app\views\search.blade.php)
First of all you are doing this
foreach ($games as $game) {
// $reviews is being updated every time in loop
$reviews = DB::table('reviews')->whereGame_id($game->id)->paginate(3);
}
So, every time there is a new value is being set to $review but it should be an array and that's why you should declare an empty array before the loop like this
$reviews = []; // or array();
foreach ($games as $game) {
$reviews[] = DB::table('reviews')->whereGame_id($game->id)->paginate(3);
}
So, you'll get an array in the $review variable.
Regarding your error message Undefined variable: reviews, it's not defined and it could be because if($input && $input != '') condition doesn't match or $games got nothing, so, try to debug step by step your code, at first make sure that execution control is being entered inside if by making dd($input) statement inside if and then if it outputs anything then make sure $games is not null/false by making a dd($games) statement after the games query.
You can change the code snippet to this
$input = Input::get('title');
if($input) {
$games = DB::table('games')->where('name', 'LIKE', "%$input%")->get();
if($games) {
$reviews = []; // or array();
foreach ($games as $game) {
$reviews[] = DB::table('reviews')->whereGame_id($game->id)->paginate(3);
}
return View::make('search', compact('reviews', 'input', 'games'));
}
}
// return a 404 (not found) or something like this or whatever, when nothing found

Laravel 4: Nest view inside layout with data

I'm writing a simple app which only relies on a few routes and views. I've setup an overall layout and successfully nested a template using the following.
routes.php
View::name('layouts.master', 'master');
$layout = View::of('master');
Route::get('/users', function() use ($layout)
{
$users = Users::all()
return $layout->nest('content','list-template');
});
master.blade.php
<h1>Template</h1>
<?=$content?>
list-template.php
foreach($users as $user) {
echo $user->title;
}
How do I pass the query results $users into my master template and then into list-temple.php?
Thanks
->nest allows a 3rd argument for an array of data:
Route::get('/users', function() use ($layout)
{
$users = Users::all()
return $layout->nest('content','list-template', array('users' => $users));
});
Also in your master.blade.php file - change it to this:
<h1>Template</h1>
#yield('content')
list-template.blade.php <- note the blade filename:
#extends('layouts.master')
#section('content')
<?php
foreach($users as $user) {
echo $user->title;
}
?>
#stop

Categories