Ferenc Straub
Ferenc Straub

Reputation: 115

Laravel 5 Eloquent relationship get the data

I have two table.

(Persons)

+------+------+ 
| id   | name | 
+------+------+ 
|  1   | John | 
+------+------+
|  2   |Albert| 
+------+------+

(Motors)

+------+------+------+ 
| id   | name |  age | 
+------+------+------+ 
|   1  |   1  |  20  | 
+------+------+------+ 
|   2  |   2  |  21  | 
+------+------+------+ 
|   3  |   1  |  20  | 
+------+------+------+

In "motors.name" i have the ids of people.

I have two models.

(Motors)

class Motors extends Eloquent
{
    public function person(){
        return $this->hasMany('App\Persons', 'id');
    }    
}

(Persons)

class Persons extends Eloquent
{
    protected $table = 'persons';
    public function motors(){
        return $this->belongsTo('App\Motors', 'name', 'id');
    }    
}

1 controller

class PrototypeController extends Controller
{
    public function names(Request $request) {
        $res = Motors::get()->person->name;
        return view('pages.prototype', compact('res'));
    }
}

1 view

<ul class="list">
    @foreach ($res as $row)     
        @if (!empty($row->name))
            <li class="list-group-item">
                {!! $row->name !!}
            </li>
        @endif
    @endforeach
</ul>

I'd like tosee the rerelational dara in view, not the ids. How can it be solved?

This code isn't good:

$res = Motors::get()->person->name;

Thanks in advance for your help.

Upvotes: 0

Views: 101

Answers (1)

Eduardo Pacios
Eduardo Pacios

Reputation: 1865

Let me try to answer this. You should try to follow conventions to make it easier to work with Laravel. Your motors.name column should be called person_id. Your model for motors table should be called Motor.php (singular of motors). The same for persons table, Person.php.

In your Motor.php file, your relationship will be:

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

If you follow conventions, you don't need to add the second parameter to the relationship name. Note that I put App\Person, you should have App\Persons if you decide to maintain the file naming you are using. In your Person.php file, your relationship will be:

public function motors(){
    return $this->hasMany('App\Motor');
}

Your foreach will be:

@foreach ($res as $row)     
    @if (!empty($row->person))
        <li class="list-group-item">
            {!! $row->person->name !!}
        </li>
    @endif
@endforeach

Note how I check:

@if (!empty($row->person))

and not:

@if (!empty($row->person->name))

It has to be done like this, because if $row->person is null, it will throw an error when you do $row->person->name

Upvotes: 2

Related Questions