0
votes

So I have two Laravel/Eloquent models, and I want to add one more field to one of them.

Model 'Car' gets data from table 'cars' and has fields 'id', 'model', 'color' and 'price'. Model 'Person' has fields 'id', 'name' and 'car_id', which is foreign key from 'cars' table. I want model 'Person' to have a field named 'car', which would contain car model from 'Car' model, depending on existing car_id. I've tried something like:

use App\Models\Car;

    class Person extends Model {

        protected $car = array(Car::find($this->car_id));
    }

But that was unsuccessful (errors like 'syntax error, unexpected '(', expecting ')''). What could be the solution? Thanks!

4

4 Answers

0
votes

You need to define One-To-Many relationship first. Then get car model for the person:

$carModel = Person::find($personId)->car->model;
0
votes

Take a look at Eloquent Relationships. What you are trying to do is to create a relationship between Car and Person models. It is up to you if a person can own one or multiple cars. I am suggesting you to let a person have multiple cars.

So, the Person model should know that it has multiple cars:

class Person extends Model
{
    public function cars()
    {
        return $this->hasMany(App\Car::class);
    }
}

A car belongs to a person, so the model should know that:

class Car extends Model
{
    public function person()
    {
        return $this->belongsTo(App\Person::class);
    }
}

Of course, when creating the tables you should add the field person_id to the CARS table.

0
votes

Well, what I needed was:

protected $appends = ['car'];

    public function getTypeAttribute($car)
    {
        return Car::find($this->car_id)->model;
    }

It was all about serialization and 'protected $appends', thank you all :)

0
votes

That's not how its done.

The person can have a car (or many). Let's suppose that every person have one car in your database, your car table should have a nullable person_id column, and add this to your User model

public function car() {
        return $this->hasOne('App\Role');
}

Now you can get the person and the his car information's like this

User::where('id',$id)->with('car')->get();

I hope you get the point here