Relationship Laravel 5.2 Eloquent

0

Good morning,

I'm having a problem in a relationship between tables with Elouquent (Laravel)

I have two tables [clients / business_activities] (innoDB MYSQL)

In the client table there is a field (FK) called: _commercial_id_id In the business_activities table there is the index: id field, along with the commercial_activity (varchar) field

When I try to retrieve the customer information, I would like to see the business activity and its related customer id along with the fields.

I'm doing this in Controller:

$return = \App\Cliente::find($id)->with('atividadesComerciais')->get();
return view('clientes.show', ['data'=>$return]);

No Model:

public function atividadesComerciais()
    {
        return $this->belongsTo('App\AtividadesComerciais', 'atividades_comerciais_id', 'id');
    }

Before I could access the information in the view by the blade so

{{ $data['razao_nome'] }}

But now it is not possible.

Where can I go wrong?

    
asked by anonymous 26.07.2016 / 16:05

2 answers

2

The belongsTo relationships of Laravel are stored in a property of your Model instance. This property will always be the name of the relationship method.

For example, if your User model relates to Role , through the User::role method, we would have the following:

class User {
     public function role() {
        return $this->belongsTo(Role::class);
     }
}

For you to access the relationship data, it would look like this:

$user = User::with('role')->find($id);

$user->role->name; // admin
$user->role->id; // 3
$user->name; // Wallace de Souza

That is, Laravel will convert the name of your relationship method to a property, which treats the relationship values, if any.

There are some important things to note:

\App\Cliente::find($id)->with('atividadesComerciais')->get();

You have set with after find . In Laravel this makes all the difference, since find is a method of Eloquent Builder , and with is a static method of Model - which in turn returns a new instance of the model itself. So, to get the desired behavior, you should use with whenever you start any query, to load the relationships "anxiously."

See:

 \App\Cliente::with('atividadesComerciais')->find(1);

If you want to load the relationship after you have done the query, you will actually use the load method.

Example:

$user = User::find(1);

$user->load('role');

$user->role->id; // 3
    
26.07.2016 / 18:34
1

You are finalizing with the get() method, this results in a collection of templates. Try changing from:

$return = \App\Cliente::find($id)->with('atividadesComerciais')->get();

for

$return = \App\Cliente::with('atividadesComerciais')->find($id);

This way with the find() method we return a single template. If you prefer, you can leave the method get() , but in the view you should use this way:

@foreach ($data as $model)
    {{ $model->razao_nome }}
@endforeach
    
26.07.2016 / 18:37