0
votes

I have an assistant and enfant tables. An assistant can have many enfants and I used a foreign key "assistant_id" to relate them. I want to display a table where every assistant has his correspondent enfants.

class Assistant extends Model
{


    protected $fillable=['username','nom', 'prenom' , 'telephone','adresse','mot_de_passe'];
    protected $dates=['created_at','updated_at'];


    public function enfants()
    {
        return $this->hasMany(Enfant::class)->select(['id','prenom']);
    }
}

And :

class Enfant extends Model
{
    protected $fillable=['username','nom', 'prenom' , 'telephone','adresse','mot_de_passe'];
    protected $dates=['created_at','updated_at'];

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

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

What to write in my view blade and controller please? I couldn't find a clear answer.

1
Did you ever resolve this issue? - FunkyMonk91

1 Answers

1
votes

Make sure you spell your class names correctly. In your example you have return $this->belongsTo('App\Parrent'); but the class name I assume is Parent based off of what you named your function.

If you want Assistants to have many enfants then the enfants model should have a property called 'assistant_id' so that they can be related by Laravel.

As for displaying in a blade template, make sure you pass the data to the view from the controller. With all the related information, I suggest you look at eager loading.

In the blade template you would then just make a table with a loop

@foreach($assistants as $assistant)
    <tr>
        <td>{{ $assistant->nom }}</td>
        <td>
            <ol>
                @foreach($assistant->enfants as $enfant)
                    <li>{{ $enfant->nom }}</li>
                @endforeach
            </ol>
        </td>
    </tr>
@endforeach