lundi 5 juin 2017

Laravel 5.4 OrderBy through a relationship

I´m triying to order by name through a relationship hasMany. If I order in second foreach, doesn't work, I´m understand that I have to do that on the first foreach but How can I do that? Maybe I can do that in the Controller but I don´t know how. This is my code:

In the view:

@foreach($data['tags'] as $tag)
        <tr>

            <td>{!! date('d-m-Y', strtotime($tag->created_at)) !!}</td>

            <td>
                @foreach($tag->langs()->orderBy('name', 'asc')->get() as $tag_lang)
                    @include('panel.partials.list_name', ['value' => $tag_lang, 'route' => 'tags.edit', 'id' => $tag->id, 'name' => $tag_lang->name])
                @endforeach
            </td>
        </tr>
    @endforeach

The relationship in Tag:

public function langs()
{
    return $this->hasMany('App\Models\LangTag');
}

The relationship in LangTag:

public function tag()
{
    return $this->belongsTo('App\Models\Tag');
}

The controller:

public function index()
    {
        $data['tags'] = Tag::paginate(25);
        return view('panel.tags.index', compact('data'));
    }



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire