samedi 27 février 2016

Laravel nested relationship foreach loops

I have this relationship betwen item and episode

item:

public function episodes()
    {
        return $this->hasMany(episode::class);
    }

episodes:

public function item()
        {
            return $this->belongsTo(item::class);
        }

In controller

$latestanimes = DB::table('episodes')->where('category', 'anime')
            ->orderBy('created_at', 'desc')
            ->take(5)
            ->get();

What I'm trying to do is get the title of the anime it belongs to of each episode

                       @foreach($latestanimes as $episode)
                              <tr>
                                <td>
                                    @foreach($episode->item as $parrent)
                                      {{  $parrent->title; }}
                                    @endforeach
                                </td>
                                <td>{{ $episode->number }}</td>
                                <td>{{ $episode->category }}</td>
                            </tr>
                        @endforeach

This gives me "Undefined property: stdClass::$item"

I tried debugging in routes.php

Route::get('/dd/{id}', function($id){

        $episode=App\episode::find($id);
        echo $episode->name. '<hr>';

        $item=$episode->item;
        echo $item->title;

    });

And this works ... Is there a way to access it directly? like

{{ $episode->item->title }}

Thanks in advance



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1n6pefm
via IFTTT

Aucun commentaire:

Enregistrer un commentaire