How to list the records of a certain employee with Laravel?

2

Hello, I happen to be taking my first steps on Laravel. I created a database with two tables (dependents and employees), created the crud of each and display the entire system in html (bootstrap). The problem is that I am not able to create a page where, when clicked on the employee button, goes to the list of dependents of that user. The ratio is 1 to N.

Using Tinker I can list, but I would like to display it on the system, in html (as I do with the general list of dependents and employees). I found this in the documentation but did not get much results in the project: link

namespace App;

use Illuminate\Database\Eloquent\Model;

class Funcionario extends Model {

    protected $fillable= [

        'codigo',
        'nome',
        'sexo'

    ];

    public function todosDependentes(){

        return $this->hasMany('App\Dependente', 'funcionario_id', 'id');

    }
}


namespace App;

use Illuminate\Database\Eloquent\Model;

class Dependente extends Model{
    protected $fillable = [

        'funcionario_id',
        'nome',
        'dataNascimento'

    ];

    public function funcionario(){

        return $this->belongsTo('App\Funcionario',  'id', 'funcionario_id');
    }

}
    
asked by anonymous 28.09.2016 / 20:22

1 answer

4

In your Model Officer do this:

public function todosDependentes(){
    $this->hasMany('App\Dependente');
}

In your Model Dependent do this:

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

When you pass the official object to your view by the controller ...

public function dependentes($id){
    $funcionario = App\Funcionario::find($id);
    return view('sua_view', compact($funcionario);
}

You can list the dependents as follows to show id pendents for example:

@foreach($funcionario->todosDependentes as $dependente)
    <p>{{ $dependente->id }}</p>
@endforeach
    
28.09.2016 / 20:52