Chonchol Mahmud
Chonchol Mahmud

Reputation: 2735

How do I get related model from collection in Laravel 5.2?

I have a method returning all job post data. This is what I have tried:

public function show($id)
{
    $applicantData = Applicant::whereId($id)->first();
    $jobData = Job::all();
    //dd($jobData);
    //dd($jobData->job_title);
    return view('applicant.confirmation',compact("applicantData","jobData"));
}

dd($jobData); returns:

image of jobData

dd($jobData->job_title); it returns an error:

ErrorException in ApplicantController.php line 150: Undefined property: Illuminate\Database\Eloquent\Collection::$job_title

How can I get the $jobData->job_title value?

Upvotes: 0

Views: 129

Answers (5)

msonowal
msonowal

Reputation: 1687

public function show($id)
{
    $applicantData = Applicant::whereId($id)->first();
    $jobData = Job::find($applicantData->job_id); //this will give you the job
    dd($jobData);
    dd($jobData->job_title);
    return view('applicant.confirmation',compact("applicantData","jobData"));
}

Upvotes: 1

Ruslan Osmanov
Ruslan Osmanov

Reputation: 21492

You should iterate collections using the each method in Laravel:

$jobData->each(function ($item, $key) {
  dd($item->job_title);
});

Upvotes: 2

Gayan
Gayan

Reputation: 3704

$jobData is a collection so you cannot directly access job_title like $jobData->job_title. I figure you want to access them in your view file. hence do following

@foreach($jobData as $job)
    {{ $job->job_title }}
@endforeach

Upvotes: 1

ujwal dhakal
ujwal dhakal

Reputation: 2459

They are object in arrays so you can directly pickout the value. If you need first item then $jobData[0]->job_title or $jobData->first()->job_title or you can loop foreach($jobData as $data){$data->job_title}

Upvotes: 1

Liam Demafelix
Liam Demafelix

Reputation: 21

You have to loop through $jobData since it will return all rows. Something like:

$jobData = Job::all();
foreach ($jobData as $job) {
    echo $job->job_title;
}

Upvotes: 1

Related Questions