Vanye Wadawasina
Vanye Wadawasina

Reputation: 47

How do i retreive the values of belongs to relationship

I want the retrieve the values of a belongsTo relationship. The values are returning but when i use for loop, it is returning object of property [] not found.

This is the returned json [user_request] on blade:

{
  "id": 2,
  "name": "henry",
  "email": "[email protected]",
  "email_verified_at": null,
  "created_at": "2019-05-15 19:04:42",
  "updated_at": "2019-05-15 19:04:42",
  "Affiliate": "FMS",
  "admin": 0
}

My code:


examrequest model
class examrequest extends Model
{
  protected $table = 'examrequest';

  public function users(){
   return $this->belongsTo('App\User','id');
  }
}


Controller
public function getRequest(){
  $request = examrequest::first()->users;

    $count = $this->isThereRequest();
    return view('admin.request', ['user_request'=>$request]);
 }

blade view
@foreach ($user_request as $key => $value )
    <tr>
     <th scope="row"></th>
     <td>{{$value->id}}</td>
     <td>{{$value->name}}</td>
     <td>{{$value->email}}</td>
     <td><button>Approve</button></td>
    </tr>
@endforeach

I want to display all the values but its returning :: Trying to get property 'id' of non-object

Upvotes: 0

Views: 44

Answers (1)

Watercayman
Watercayman

Reputation: 8178

If you are looking for a collection to loop through, you won't get that if you use first(), as this won't pull a collection, but rather a single object. Change

$request = examrequest::first()->users;

to

$request = examrequest::with('users')->get();

The collection of examrequests will all be inside $request at this point.

On the blade side, if you want to loop on that collection and pull each user, you can simplify by just pulling the user from the foreach. Change:

@foreach ($user_request as $key => $value )

to

@foreach ($user_request as $request )

and then pull the fields you need from the user relation on the $request object: $request->users->id... etc within the loop on the blade page.

Upvotes: 1

Related Questions