0

I am trying to show user data in my view . my view

<table class="table table-striped">
              <thead>
                <tr>
                  <th> Name </th>
                    ....
                </tr>
              </thead>
              <tbody>
                @foreach($users as $user)
                <tr>
                  <td> {{$user->user_name}} </td>
                  ....
                </tr>
                @endforeach
              </tbody>
            </table>

my controller

$user=UserModel::where('user_id',$user_id)->get();

        return view('index')->with('users',$user));

dump returns me that

Illuminate\Database\Eloquent\Collection {#1244 ▼
  #items: array:1 [▼
    0 => App\Models\usersModel {#1249 ▼
      #table: "users"
      #fillable: array:15 [▶]
      #connection: "mysql"
      #primaryKey: "id"
      #keyType: "int"
      +incrementing: true
      #with: []
      #withCount: []
      #perPage: 15
      +exists: true
      +wasRecentlyCreated: false
      #attributes: array:18 [▶]
      #original: array:18 [▶]
      #changes: []
      #casts: []
      #classCastCache: []
      #dates: []
      #dateFormat: null
      #appends: []
      #dispatchesEvents: []
      #observables: []
      #relations: []
      #touches: []
      +timestamps: true
      #hidden: []
      #visible: []
      #guarded: array:1 [▶]
    }
  ]
}

when I try to fetch data of users from database it returns me that error "trying to get property of non object". I am currently using laravel 7

alex
  • 123
  • 8
  • This means that `$user` is not an object, as should be clear from the error. Check that your data is in the expected format. Perhaps `dump($user)` might give you some ideas. The duplicate has details at https://stackoverflow.com/a/26572398 – miken32 Mar 15 '21 at 19:53

1 Answers1

-1

Laravel has his own User Model, if you enabled it you can call the user information simply with

Auth::user()->user_name

if this do not work: Is your query returning array or object? If you dump it out, you might find that it's an array, so all you need is an array access [] instead of an object access (->).

Daniel Juric
  • 128
  • 1
  • 10