Search code examples
laravelvieweloquentmodels

What is the best way to send a nested array of a model in Laravel 4?


I'm creating a simple blog with a list of posts. Each post has multiple medias (images, videos, etc.). So I have three models: Post (id, title, article, album_id, etc.), Album (id, title, description, etc.) and Media (id, url, type, etc.). A post may have an album and an album can have multiple medias.

To generate the page with list of posts I coded as follows (BlogController):

public function generateList(){
        $posts = Post::where('subcategory_id','=','3')->orderBy('created_at', 'DESC')->paginate(30);

        return View::make('main.informativos')
            ->with('posts', $posts);
    }

As you can see, today only the posts are sent to the view. My question is: what is the best way to send all the medias of each post? Remembering that there many posts.


Solution

  • Specify the foreign keys probarly in models
    use relationship functions with 'foreignkey', 'primarykey'
    use with function in controller before where condition
    company, country functions are based on relationships
    Again you have doubt.. check laravel doc

    public function index()
    {
        $Location = Location::with('Company', 'Country')
            ->where('company_id', '=', $company_id)
            ->get();
        return response()->json($Location, 200);
    }