mercredi 2 mars 2016

Laravel's Eager Loading is bringing all data from database

I have a Post model that belongs to a Category model. I also have an index page that lists all the Posts, and for each one I need to print the name of the Category it belongs to.

class Post extends Model
{
    public function category()
    {
        return $this->belongsTo(Category::class);
    }
}

class Category extends Model
{
    public function posts()
    {
        return $this->hasMany(Post::class);
    }
}

My PostController::index

public function index()
{
    return \View::make('admin/post/index')->with([
        'posts' => \DB::table('posts')->orderBy('id', 'DESC')->get(),
        'category' => Post::with('category')->get()
    ]);
}

Like this, if I echo the $category, it shows all registered categories inside of each row in Post. I don't know what I can do in the view to show the correct name of the category for each Post.

I did this in my view, but like this, it only shows the x register of the table for every Post:

@foreach ($posts as $post)
    <tr>
        <td>
            <a href="/admin/post/view/{{ $post->id }}">
                {{ $post->title }}
            </a>
        </td>
        <td>
            {{ str_limit($post->content, 120) }}
        </td>
        <td>
            {{ $category[1]->category->category }}
        </td>
        <td>
            {{ date('m/d/Y', strtotime($post->created_at)) }}
        </td>
        <td>
            <a href="/admin/post/edit/{{ $post->id }}" class="btn btn-primary">
                Edit
            </a>
            <a href="/admin/post/delete/{{ $post->id }}" class="btn btn-danger">
                Delete
            </a>
        </td>
    </tr>
@endforeach

How do I properly print the name of the Category, which is related to Post, with Laravel 5.2 using Eager Loading?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire