Yusei
Yusei

Reputation: 27

Laravel Eloquent: Getting JSON data from 2 tables

I have 2 tables

like below: Tables I want to get JSON data like below from the tables by Eloquent.

[
    {
        “id”: 1,
        “name”: “festival name 1”,
        “url”: [
            “https://picsum.photos/480/480/?image=51”,
            “https://picsum.photos/480/480/?image=52”,
            “https://picsum.photos/480/480/?image=53”
        ]
    },
    {
        “id”: 2,
        “name”: “festival name 2”,
        “url”: [
            “https://picsum.photos/480/480/?image=54”,
            “https://picsum.photos/480/480/?image=55”,
            “https://picsum.photos/480/480/?image=56”
        ]
    }
]

Can anyone please tell me how to do this in Laravel 5.7?

This is FestivalController.php

class FestivalController extends Controller{
    public function getFestivals(){
        //I want to know how to do...
        return $festivals->toJson();
    }
}

Upvotes: 0

Views: 691

Answers (2)

Thamer
Thamer

Reputation: 1954

First, I assume that you have already defined the relationship between festival and festival_images.

just to clarify :

Festival Model :

please change the name of the place of your Festival Image Model:

use App\Models\FestivalImage;

public function festivalImages()
{
   return $this->hasMany(FestivalImage::class);
}

then your getFestivals controller method

public function getFestivals(){

     $festivals = Festival::with('festival_image')->get();

     $festivals = $festivals->map(function($f){

     $festival =  [
           "id" => $f->id,
            "name" => $f->name,
            "urls" => $f->festivalImages->toArray() ,
     ];

     return $festival;

     });

     return $festivals->toJson();
}

Upvotes: 1

rock-star
rock-star

Reputation: 88

First in your model of festival you need to define a relationship between festival_image.

'festival Modal'

public function festival_image()
    {
        return $this->HasMany('App\YourModalName', 'id', 'festival_id');
    }

Then on your controller You call the model festival and you will see it will have the festival_image. With something like this

$festival = App\YourModalName::all();

$image = $festival->festival_image();

return $image

You can then just return and you will get laravel to take care of turning it to JSON. Or you can go

return response()->json($image);

More - Read here.

https://laravel.com/docs/5.8/eloquent-relationships#has-many-through

Upvotes: 2

Related Questions