How to list the depedents of a particular employee with Laravel?

Asked

Viewed 194 times

2

Hi, I happen to be taking my first steps on the Laravel. I created a database with two tables (dependents and employees), created the crud of each and display the whole 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 this user. The ratio is 1 to N.

Using Tinker I can list, but I would like to display it in 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 many results in the project: https://laravel.com/docs/5.3/eloquent-relationships#querying-Relations

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');
    }

}
  • Put both Models in your question!!!

  • 1

    edited the post

  • The answer made clarifies you, yes no and why?

  • 1

    Yes, thank you very much!

1 answer

4


In his Model Funcionario do this:

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

In his Model Dependente do this:

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

When you pass the object staff for your view by 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 the id of dependents for example:

@foreach($funcionario->todosDependentes as $dependente)
    <p>{{ $dependente->id }}</p>
@endforeach
  • Sorry for the late feedback, only now I could test. It worked really well, I am immensely grateful! I thought it was strange because the same way you did I had done it but it always gave "Undeclared variable" error in the view, but I believe the problem was in foreach(). Once again, thank you very much!

  • You’re welcome @Ramones glad it worked!

Browser other questions tagged

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