0

Invalid argument supplied for foreach()

My Controller function

use App\Tag

public function index()
{
    //
    $tags = Tag::all();
    return view('tags.index')->withTags('$tags');
}

Index view blade

@foreach ($tags as $tag)
<tr>
<th>{{ $tag->id }}</th>
<td>
<a href="{{route('tags.show', $tag->id)}}">{{ $tag- >name }}</a>
</td>
</tr>
@endforeach
Salman Zafar
  • 3,844
  • 5
  • 20
  • 43
  • 1
    `'$tags'` would be a literal `$tags`. – Devon Bessemer Sep 11 '18 at 13:56
  • 1
    Possible duplicate of [What is the difference between single-quoted and double-quoted strings in PHP?](https://stackoverflow.com/questions/3446216/what-is-the-difference-between-single-quoted-and-double-quoted-strings-in-php) – Devon Bessemer Sep 11 '18 at 13:56

2 Answers2

3

Just remove the single quotes and Tags in withTags('$tags') so it becomes:

public function index()
{
    $tags = Tag::all();
    return view('tags.index')->with('tags', $tags);
}

or you could use compact and do what Salman said.

3

use compact it's easier and simpler try the below code:

public function index()
{
    //
    $tags = Tag::all();
    return view('tags.index',compact('tags'));
}

if you want to use with then try below code:

public function index()
    {
        //
        $tags = Tag::all();
        return view('tags.index')->with('tags',$tags);
    }

in blade you can do what you are doing or you can use forelse try the below code:

@forelse($tags as $tag)
<tr>
<th>{{ $tag->id }}</th>
<td>
<a href="{{route('tags.show', $tag->id)}}">{{ $tag- >name }}</a>
</td>
</tr>
@empty
<div class='alert alert-danger'>
  No tags..!
</div>
@endforelse
Salman Zafar
  • 3,844
  • 5
  • 20
  • 43