1

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);
;
}
4
  • 1
    Umm off-topic maybe but why do you have that extra semicolon inside you Controller? On-topic is your $task traversable? dd($task) before the foreach inside blade. Commented Jan 15, 2017 at 2:04
  • @Mihailo that was not off-topic mate. Commented Jan 15, 2017 at 5:48
  • @linuxartisan's answer is correct. You cannot expect to receive a collection from $task = Task::find($id);. It just returns the matching Task object Commented Jan 15, 2017 at 5:51
  • @steven If you have resolved this problem, please accept the answer that helped you; so that the question doesn't stay open. Commented Feb 3, 2017 at 2:46

4 Answers 4

2

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
Sign up to request clarification or add additional context in comments.

Comments

1

I Never seen to set variable like you, try this

 return view('tasks.show')->with('task', $task);

Comments

0

Reverse the foreach variables

@foreach ($tasks as $task)
   <td> {{ $task->name }} </td>
@endforeach

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.