Practical Example of Working with Eloquent in Laravel 5.6 (Relationships)

Asked

Viewed 114 times

0

I have an entity that is employees and other 3 tables that are Sector, Office and Department and the relationship is 1 for N (i.e., the primary keys of these 3 tables must become foreign in the official table).

In my View in the employee register has a select for each of those entities (Office, Sector and Dpt) that must be populated with the records already registered in the bank.

But I couldn’t make the relationship and I don’t know what I could call the method in View. Gives way that I made here he appeared the id of the position and not the name of the position and when I erased the record of View left the select, ie I’m doing wrong pulling the View and not from the bank as it should be. Could you help me?

I will post the Employee and Position Model and also the part of View where "fill" the select

EMPLOYEE MODEL

<?php

namespace App\Models\Treinamento;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;


class Funcionario extends Model
{
    protected $fillable = [

        'nome_funcionario', 'email_funcionario', 'instrutor', 

    ];  

         protected $guarded = [

            'id', 'cargos_id', 'setors_id', 'departamentos_id' 

            ];  
                protected $table = 'funcionarios';


    use SoftDeletes;

    protected $dates = ['deleted_at'];



}

ROLE MODEL

<?php

namespace App\Models\Treinamento;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class Cargo extends Model
{
    protected $fillable = [
        'nome_cargo'
    ];
    protected $table = 'cargos';


    use SoftDeletes;

    protected $dates = ['deleted_at'];



}

PART OF THE VIEW (SELECT POSITION)

div class="row">
         <div class="col-md-4">
             <strong>Selecione o Cargo</strong>
          <select name="cargos_id" class="form-control" required="ON">
                            <option value="">Clique aqui</option>

       @foreach ($classcargo_array as $cargos_id)
        <option value="{{$cargos_id->id}}" > {{$cargos_id->nome_cargo}} 
        </option>
               @endforeach 
                 </select>    

                        </div>

1 answer

0


For inverse one-to-many relations, you use the relationship function belongsTo, this way in class Funcionario:

public function cargo()
{
    return $this->belongsTo(\App\Models\Treinamento\Cargo::class, 'cargos_id', 'id');
    // O primeiro parametro é a Model(Cargo) que se relaciona.
    // O segundo, é a foreign key, coluna nessa classe(Funcionario) que identifica a Model.
    // O terceiro, é a local key, a coluna na Model(Cargo) que identifica ela.
}

That way, when you carry one Funcionario and want to get the information from Cargo of it, you use the -> for the relationship belongsTo returns an instance of the class Cargo, thus:

$funcionario->cargo->nome_cargo

Detail, you define a function for the relation but to use you call it as if the function were a property.

To the Cargo get the Funcionario related to it, you would use the One-to-Many relationshiphasMany and add the following function to the Cargo:

public function funcionarios()
{
    return $this->hasMany(\App\Models\Treinamento\Funcionario::class, 'cargos_id', 'id');
    // O primeiro parametro é a Model(Funcionario) que se relaciona.
    // O segundo, é a foreign key, coluna na Model(Funcionario) que identifica essa classe.
    // O terceiro, é a local key, a coluna nessa classe(Cargo) que identifica ela.
}

And to manipulate the Funcionario related to the Cargo, you use the foreach for the relationship hasMany returns a collection of Funcionario, thus:

foreach($cargo->funcionarios as $funcionario){
    // Algum código...
}

As for your view, if you want to get all Cargo added and display them in the tag option, you use the following code in the function in your Controller in which is returning to view of registration of Funcionario:

...
$cargos = \App\Models\Treinamento\Cargo::all();
return view('view_de_cadastro_de_funcionario', compact('cargos'));

And in his view, you display them in the same way as you wrote in the answer with the names changed, so:

@foreach ($cargos as $cargo)
    <option value="{{ $cargo->id }}">{{ $cargo->nome_cargo }}</option>
@endforeach 
  • Thank you very much, Vinicius. I think I’m still doing something wrong because I got this error back in the view: Errorexception (E_ERROR) Undefined variable: Undefined variable: positions

  • @Devphp It was my mistake, I forgot to add the function compact, now I fixed in the answer and now should work smoothly. To pass values to the view, type the variable $cargos, the second parameter should look like this ['positions' => $positions]. Using the helper compact it makes this process automatically.

  • 1

    Just a little tip. Compact is a native function of PHP and not a helper of the Laravel. https://secure.php.net/manual/en/function.compact.php

Browser other questions tagged

You are not signed in. Login or sign up in order to post.