Hesham
Hesham

Reputation: 35

Laravel : @foreach Undefined variable

i have error but in foreach :Undefined variable: infos that's my View :

@foreach ($infos as $info)
    <tr>
        <td>{{ $info->id }}</td>
        <td>{{ $info->name}}</td>
        <td>{{ $info->code }}</td>
        <td>{{ $info->phone }}</td>
        <td>{{ $info->phone2 }}</td>
    </tr>
@endforeach

and my controller

    public function index()
    {
        $info = Info::latest()->get();
        return view('info.admin')->with('infos', $info);
    }

Upvotes: 0

Views: 181

Answers (3)

Pavel Lint
Pavel Lint

Reputation: 3527

You should pass parameters to the view like this:

   return view('info.admin', ['infos' => $infos]);

What you've been doing before using with has a different effect, it flashes the data to the session. Check out this doc here

Upvotes: 1

Nitin Sharma
Nitin Sharma

Reputation: 419

You can use forelse will be better:

@forelse($infos as $key => $info)
    <tr>
        <td>{{ $info->id }}</td>
        <td>{{ $info->name}}</td>
        <td>{{ $info->code }}</td>
        <td>{{ $info->phone }}</td>
        <td>{{ $info->phone2 }}</td>
    </tr>
@empty
    <tr>
        <td>Data Not Found</td>
    </tr>
@endforelse

Controller:

public function index()
{
    $info = Info::latest()->get();
    return view('info.admin')->with(['infos'=> $info]);
}

Upvotes: 0

mustafaj
mustafaj

Reputation: 305

Check if the following code gives you the "There are no infos". If it does, that means that the $infos variable in the controller is not returning data, and thus giving you the error

@if(empty($infos))
    <tr><td>There are no infos</td></tr>
@else
   @foreach ($infos as $info)
        <tr>
            <td>{{ $info->id }}</td>
            <td>{{ $info->name}}</td>
            <td>{{ $info->code }}</td>
            <td>{{ $info->phone }}</td>
            <td>{{ $info->phone2 }}</td>
        </tr>
    @endforeach
@endif

Upvotes: 0

Related Questions