Parul
Parul

Reputation: 41

Undefined variable: in laravel 6

I am trying to Display data on Laravel view page from database.

but it shows nothing to me

this is the code on .blade.php file:-

   <tbody>
   @if(isset($Us))
       @foreach($Us as $row)
           <tr>
               <td>{{ $row->id ?? '-'}}</td>
               <td>{{ $row->name ?? '-' }}</td>
               <td>{{ $row->email ?? '-'}}</td>
           </tr>
       @endforeach
   @endif
   </tbody>
</table>

Code on AdminController.php:

public function index()
{
    $Us = users::all()->toArray();
    return view('master')->with(['Us'=> $Us]);
}

and on user.php:

class Us extends Model
{
    protected $fillable = ['id','name','email'];

    public function category(){
        $this->belongsTo(Category::class);
    }
}

i wanted to show database info to admin page

Thank you

Upvotes: 2

Views: 419

Answers (2)

lagbox
lagbox

Reputation: 50491

You have converted the Eloquent Collection to an array which converts all the model instances it contains to arrays. In your Blade file you are trying to access the elements of the array as objects when they are also arrays. Use the syntax for accessing an array by index, $array['index'], instead of an object's property, $object->property:

<td>{{ $row['id'] ?? '-'}}</td>
<td>{{ $row['name'] ?? '-' }}</td>
<td>{{ $row['email'] ?? '-'}}</td>

Would probably be easier to just not convert the Collection to an array with toArray.

Demonstration of the issue:

$a = ['a' => 'A'];

dump($a->a ?? '-');
dump($a['a'] ?? '-');

Upvotes: 0

user11962879
user11962879

Reputation:

Try to change your model name to User instead of Us and users::all() to User::all()

Upvotes: 1

Related Questions