Reputation: 51
I try to build my own project which is job online website.
I have two tables company
and job
.Table company
can have many jobs relationship
Here is relationship
//company.php
public function jobs(){
return $this->hasMany(Job::class);
}
//job.php
public function company(){
return $this->belongsTo(Company::class);
}
My tables
Schema::create('companies', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id');
$table->string('companyName');
$table->string('logo')->nullable();
$table->string('contactPerson');
$table->string('employeeSize');
...
Schema::create('jobs', function (Blueprint $table) {
$table->increments('id');
$table->integer('company_id');
$table->string('jobTitle');
$table->longText('jobDescription');
$table->longText('jobRequirement');
$table->date('deadline');
...
I want to display all jobs and every job has its own company like
what is the code in controller and in the view would be? please help!
Upvotes: 1
Views: 148
Reputation: 392
Controller:
public function index()
{
$jobs = Job::all();
return view('index', compact('jobs'))
}
View:
<ul>
@foreach($jobs as $job)
<li>{{$job->jobTitle}}</li>
<li>{{$job->deadline}}</li>
<li>{{$job->company->companyName}}</li>
<li>{{$job->company->logo}}</li>
@endforeach
</ul>
Upvotes: 0
Reputation: 40909
You can access job's company by simply accessing $job->company. You could also optimise fetching data from the database with eager loading:
$jobs = Job::with('company')->get();
foreach ($jobs as $job) {
echo $job->title;
echo $job->company->name;
}
Upvotes: 1