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

0

I have an entity that is employees and 3 other tables that are Sector , Position and Department and the relationship is 1 for N (that is, the primary keys of these 3 tables must be foreign in the employee table).

In my View in the employee's registry has a select for each of these entities ( Position , Sector and Dpt ) which must be populated with the records already registered in the bank.

But I could not make the relation and I do not know how I could call the method in View . So I did it here it appeared the job id and not the job name and when I deleted the registry of View it left the select, ie I'm doing wrong by pulling View and not the bank as it should be. can you help me?

I will post the Employee and Charge Model and also the share of View where "fill in" 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'];



}

POST 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 (POST SELECT)

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>
    
asked by anonymous 16.09.2018 / 04:38

1 answer

0

For inverse One-to-Many relationships, you use the belongsTo relationship function, this way in the Funcionario class:

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 load Funcionario and want to get the Cargo information from it, you use -> because the belongsTo relation returns an instance of the Cargo class, like this:

$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.

For Cargo get the Funcionario related to it, you would use the One-to-Many hasMany relation and add the following function in the Cargo class:

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 Funcionario related to Cargo , you use foreach because hasMany returns a collection of Funcionario , like this:

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 option tag, you use the following code in the function in your Controller where you are returning view of Funcionario :

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

And in your view , you display them the same way you typed in the response with the changed names, like this:

@foreach ($cargos as $cargo)
    <option value="{{ $cargo->id }}">{{ $cargo->nome_cargo }}</option>
@endforeach 
    
16.09.2018 / 06:15