matsutus
matsutus

Reputation: 74

Trouble understanding laravel eloquent models

It's been a some time since I've programmed with Laravel and I'm stumped by the relations I need in order to create a foreign key -link with 2 models.

I have a database where there's a table "company" containing companies, and I also have a table called "projects", which contains projects.

So the Projects- table contains a column called "employercompany" with a foreign key constraint to the company-table.

I'm trying to print out the company's name in a project page in laravel with

{{$project->employercompany->name}}

But keep getting "Trying to get property of non-object"

My model pages look like this:

//Company

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Company extends Model
{
   public function projects()
   {
       return $this->hasMany('App\Projects', 'employercompany', 'id');
   }
}

and

// Projects

namespace App;

use Illuminate\Database\Eloquent\Model;

class Projects extends Model
{
    public function employercompany()
    {
        return $this->belongsTo('App\Company');
    }
}

I know this is an easy problem but I just can't wrap my head around it

*****EDIT*****

I found the solution. Thanks Radical for providing some insight.

I ended up changing the employercompany column to company_id and, all the others as such too.

After that I fiddled around what I'm guessing fixed the thing was that I changed my database search query from

DB::table('projects')->get();

into

Project::all();

Don't know if that was the change needed but it sure feels like it was.

Upvotes: 0

Views: 73

Answers (2)

Radical
Radical

Reputation: 1073

When defining a belongsTo relation like you have done, Laravel will try and 'guess' the keys you are using based on the class name. In this case, it will look for a column company_id on your Projects model since your model is called Company.

Like you have done for the projects() method on your Company model, you should tell Laravel that you are using the employercompany column to reference the Company model:

public function employercompany()
{
    return $this->belongsTo('App\Company', 'employercompany');
}

For more information, see the relevant documentation here.

In addition, to make things easier, it might be worthwhile to try - if possible - to adhere to what Laravel 'expects' your database columns to be called, so situations like this are resolved automatically.

Upvotes: 1

Zedex7
Zedex7

Reputation: 1672

It should be like

$project = Project::find($id); //id of project

$compnany_name = ($project->employercompany()->get())->name;

Upvotes: 0

Related Questions