How model relationships works with blades?

Refresh

5 weeks ago

Views

22 time

0

I have a model 'applicants' and it has a 'belongsTo' relationship with 'BloodGroup' model.

Here is the index function from ApplicantController:

    public function index()
    {
        $user = Auth::user();

        // $user = User::find(1);
        $applicants = $user->applicants->where('visible', 1);

        foreach ($applicants as $applicant) {
            $applicant->bloodGroup;
            $applicant->fiqa;
            $applicant->gender;
        }
        // return response()->json($applicants);
        return view('applicants.index', ['applicants' => $applicants]);
    }

Here is the response that I get from the API:

{
    "1": {
        "id": 4,
        "blood_group_id": 1,
        "created_at": "2019-04-22 13:24:16",
        "updated_at": "2019-04-26 10:21:41",
        "blood_group": {
            "id": 1,
            "name": "A+",
            "visible": 1,
            "created_at": "2019-04-22 08:21:19",
            "updated_at": "2019-04-22 08:21:19"
        }
    }
}

But when I pass data to the view. It generates an error in the following lines:

    <div class="row mx-4">
       <div class="col-06 pr-3">
          <p class="h5">Name:</p>
       </div>
       <div class="col-06">
          <p><?php echo e($applicant->blood_group->name); ?></p>
       </div>
    </div>

BloodGroup Model:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class BloodGroup extends Model
{
    public function applicants()
    {
        return $this->hasMany('App\Applicant');
    }
}

BloodGroup relationship in Applicants table:

public function bloodGroup()
{
    return $this->belongsTo('App\BloodGroup');
}

Can you please point out what I'm doing wrong and how this should be done.

1 answers

0

What is the error that it says?

return view('applicants.index', ['applicants' => $applicants]);

You are passing applicants to the view but you use $applicant in it. Are you looping over $applicants? If no that's the error.