error from laravel's foreach loop - php

Getting error message from Laravel's foreach loop:
Invalid argument supplied for foreach()
My foreach loop is :
#foreach ($task as $tasks)
<td>{{$tasks->name}}</td>
#endforeach
My controller is:
public function show($id){
$task = Task::find($id);
return view('tasks.show')->withTask($task);
;
}

You are giving a wrong data type to the foreach loop.
A foreach requires an array or a Collection.
The statement
$task = Task::find($id);
will give you a Task model (not a Collection).
Hence you cannot iterate over it.
Also, since you are trying to display the Task resource (assuming this as you are calling the controller's show() function), you don't need to iterate over the model - as you will be displaying a single entity's attributes.
Just do this
Controller:
public function show($id){
$task = Task::find($id);
return view('tasks.show', compact('task'));
}
In the view:
Name: {{ $task->name }}
// other attributes here

I Never seen to set variable like you, try this
return view('tasks.show')->with('task', $task);

Reverse the foreach variables
#foreach ($tasks as $task)
<td> {{ $task->name }} </td>
#endforeach

You should write this. This will solve your problem
Your Controller
public function show($id){
$task = Task::findOrFail($id);
return view('tasks.show', compact('task'));
}
As it gets only one value so no need to use foreach. You should write this
<td>{{$tasks->name}}</td>
The findOrFail method return only one value. So No need to loop it.
Hopefully this will solve your problem.

Related

Display users with relations in foreach loop

I want to display all my users with relations. Currently I have:
FilterController.php
public function getFilter($sport)
{
$user = Auth::user();
$users = $this->model->getUsersByDiscipline($sport);
return view('filter.' . $sport, compact('user', 'users'));
}
User.php
public function getUsersByDiscipline($sport)
{
$users = User::with('user_data', 'languages')->where('discipline', $sport)->get();
return $users;
}
And I try to display it like:
{{$user->user_data->employment}}
But there's error:
Property [employment] does not exist on this collection instance
How to do it correctly?
If employment is a relationship, I think it's not loaded yet. So you may load using nested eager loading.
In your eloquent query, you can use this:
$users = User::with('user_data.employment', 'languages')->where('discipline', $sport)->get();
Notice the dot syntax meaning employment is a relationship of user_data, it will now be loaded and accessible through: $user->user_data->employment
Reference: https://laravel.com/docs/5.5/eloquent-relationships#nested-eager-loading
$users = User::with('user_data', 'languages')->where('discipline', $sport)->get();
by doing this you will get the array of $users
so you need to run a loop
#foreach($users as $user)
{{ $user->user_data()->employment }}
#endforeach
Or you can debug a code in control
$users = User::with('user_data', 'languages')->where('discipline', $sport)->get();
foreach($users as $user){
dd($user->user_data()); //check what it returns in user_data;
}

Invalid argument supplied for foreach() in view file

may i know why this code showing invalid argument supplied for foreach() and how i should correct it ?
#foreach($project_details as $project) {
#foreach($project->projectusers as $users) {
{{ $user->name }}
}
#endforeach }
#endforeach
Controller
public function index()
{
$this->project = Project::with('projectusers')->get();
return view('projects.index', [
'project_details' => $this->project
]);
}
projectusers is a relationship ? Do you use the with() function in your Eloquent query to get that relationship within the collection ?
In addition, in your foreach code, you use the plural for users ($project->projectusers as $users), and then in the double brackets, you use the singular {{ $user->name }}
Remove the 's' from users in the foreach and it should work.
I would suggest reading up on foreach() a little more:
http://php.net/manual/en/control-structures.foreach.php
But if this is your entire code, you have not set any array values or assigned any values from a database or anything
$arr = array(1, 2, 3, 4);
Using the website above you can see it is quite simple to fill an array yourself depending on how many values you need to be added.
Just use compact as a second argument of your view()
public function index()
{
$projects = Project::with('projectusers')->get();
return view('projects.index', compact('projects'));
}
Then in your projects.index just call :
#foreach($projects as $project) {
#foreach($project->projectusers as $users) {
{{ $user->name }}
}
#endforeach }
#endforeach
Try this one:
public function index() {
$projects = Project::whereHas('user')->get();
return view('projects.index', compact('projects''));
in your blade:
#foreach($projects as $project)
{{$project->user->name}}
#endforeach

I cant send a variable to Blade in Laravel 5.1

I'm trying to send a variable to blade view, but throw this error:
Undefined variable: data (View: D:\wamp\www\tienda\resources\views\cliente.blade.php)
This is my Route:
Route::resource('cliente','ClienteController');
This is my Controller Cliente:
public function index(){
$data = Cliente::all();
return view('cliente',compact($data));
}
And my Blade:
#foreach ($data as $user)
<tr>
<td>{{$user->nombre}}</td>
</tr>
#endforeach
What I'm doing wrong?
Additionally, if a try to do for example this
Controller Cliente:
public function index(){
return view('cliente', ['name' => 'James']);
}
And Blade:
{{$name}}
That yes work... Only the variables and arrays, doesnt work.
Try this on your Controller:
public function index(){
$data = Cliente::all();
return view('cliente',compact('data'));
}
From the compact documentation: "Each parameter can be either a string containing the name of the variable, or an array of variable names. The array can contain other arrays of variable names inside it; compact() handles it recursively. "
you can try this way
public function index(){
$data['data'] = Cliente::all();
return view('cliente', $data);
}
Then you can catch it in blade as like this
#foreach ($data as $user)
<tr>
<td>{{$user->nombre}}</td>
</tr>
#endforeach

Trouble retrieving data laravel4(oneToMany)

Okay so I just started learning Laravel and its fantastic. I just got stuck trying to retrive all the post from a user. Here is my code
models/User.php
public function posts()
{
$this->hasMany('Post');
}
models/Post.php
public function user()
{
$this->belongsTo('User');
}
controller/UserController.php
public function getUserProfile($username)
{
$user = User::where('username', '=', $username)->first();
$this->layout->content = View::make('user.index', array('user'=>$user));
}
views/user/index.blade.php
<div class="show-post">
<ul>
<li>{{ $user->posts }}</lo>
</ul>
</div>
I also tried:
#foreach($user->posts as $post)
<li>{{$post->post}}</li>
#endforeach
So im having trouble displaying the post for each specific user. Thank you.
So with the help of #WereWolf- The Alpha I was able to solve it and make my code better, If you notice I forgot to return my relationship functions. example:
Notice I hadn't returned it before
models/Post.php
public function users()
{
return $this->belongsTo('users');
}
But also the way I was querying my database was inefficient so Alpha showed me Eager Loading
http://laravel.com/docs/eloquent#eager-loading
example of controller
public function getUserProfile($username)
{
$user = User::with('posts')->where('username', '=', $username)->first();
$this->layout->content = View::make('user.index', array('user'=>$user));
}
and finally the view:
div class="show-post">
#foreach($user->posts as $post)
{{ $post->post }}
#endforeach
</div>
Actually $user->posts returns a collection of Post model so when you try this
{{ $user->posts }}
Laravel tries to echo that collection object which is not possible. You may try foreach loop instead:
#foreach($user->posts as $post)
{{ $post->somepropertyname }}
#endforeach
It's also possible to do something like this:
// Get first post->somepropertyname
{{ $user->posts->first()->somepropertyname }}
// Get last post->somepropertyname
{{ $user->posts->last()->somepropertyname }}
// Get first post->somepropertyname (same as first)
{{ $user->posts->get(0)->somepropertyname }}
// Get second post->somepropertyname from collection
{{ $user->posts->get(1)->somepropertyname }}
// Get the post->somepropertyname by id (post id) 2
{{ $user->posts->find(2)->somepropertyname }}
Also you may use eager loading like this (better):
$user = User::with('posts')->where('username', '=', $username)->first();
You may like this article about Cocllection.
Update: Also use return in model methods, like:
public function posts()
{
return $this->hasMany('Post');
}

Laravel belongsTo returns, put can't save in var

I'm trying to get the username by a item with belongsTo.
I have this in my Item model:
public function user()
{
return $this->belongsTo('User', 'user_id', 'id');
}
And this in my controller:
$user = $item->user->username;
But I get:
Trying to get property of non-object
And when I do:
return $item->user->username;
In my controller it works.
What can be wrong?
Controller/Model: http://pastebin.com/qpAh8eFd
You have following function in your controller:
public function index($type)
{
$items = $this->item->where('type', '=', $type)->get();
foreach($items as $item):
$user = $item->user->username;
endforeach;
return View::make('items.index', ['items' => $items, 'user' => $user]);
}
You don't need to do a foreach look in the controller and whatever you are doing you are doing it wrong, instead make your index function like this:
public function index($type)
{
$items = $this->item->where('type', '=', $type)->get();
return View::make('items.index', ['items' => $items]);
}
Pass only $items to your items/index.blade.php view. You may do a foreach loop in your view if needed and within each iteration you may access the user related to the item using something like this:
#foreach($items as $item)
{{ $item->user->uername }}
#endforeach
You may get Trying to get property of non-object error message because each $item may don't have a related user. So, make sure each $item has a related user. You can also, use following to get items with user:
$items = $this->item->with('user')->where('type', '=', $type)->get();
return View::make('items.index', ['items' => $items]);
In your view you may check if the item has a related user:
#foreach($items as $item)
#if($item->user)
{{ $item->user->uername }}
#endif
#endforeach

Categories