How to merge object and array in one controller laravel - laravel

I got like this
[
{
"NameProduct": "iphone",
"IDProduct": 1,
"ListPrice": 100000,
"ImagePath": "iphone.png"
},
[
{
"IDCollection": 5,
"NameCollection": "Phone",
"Description": "my description",
}
],
{
"NameProduct": "SamSung",
"IDProduct": 2,
"ListPrice": 379000,
"ImagePath": "samsung.png"
},
[
{
"IDCollection": 5,
"NameCollection": "Phone",
"Description": "my description",
}
],
But I want like this:
{
"IDCollection": 5,
"NameCollection": "Phone",
"ProductList": [
{
"NameProduct": "iphone",
"IDProduct": 1,
"ListPrice": 100000,
"ImagePath": "iphone.png"
},
{
"NameProduct": "SamSung",
"IDProduct": 2,
"ListPrice": 100000,
"ImagePath": "samsung.png"
},
]
}
This is my code:
public function show(int $id)
{
$product=[];
$product_collection = CollectionProduct::where('IDCollection',$id)->get();
$collection = Collection::where('IDCollection',$id)->get();
foreach ($product_collection as $items) {
$x = Product::select('NameProduct','IDProduct','ListPrice')->find($items['IDProduct']);
$x->ImagePath = ProductImage::where('IDProduct',$items['IDProduct'])->first()['Path'];
array_push($product, $x,$collection);
}
return response()->json($product);
}
and idea how do that ?

You can use Eager Loading to get the relationships of CollectionProduct. https://laravel.com/docs/9.x/eloquent-relationships#eager-loading
For help you with the code I need to see your relationships of the DB but I think this can help you:
public function show(int $id)
{
$product_collection = CollectionProduct::with('collection.product.productImage')
->where('IDCollection',$id)
->get();
return response()->json($product_collection);
}

Related

Laravel 9 Rest API - pagination meta tag unavaible when return it with response()

Controllers/Komic Controller
public function search($value)
{
// Query Wildcards and Resources
$result = new KomikCollection(Komik::where('judul', 'like', '%'. $value .'%')->paginate(2));
return $result;
}
its fine when i directly return the $result
{
"data": [],
"links": {
"first": "http://localhost:8000/api/komik/a?page=1",
"last": "http://localhost:8000/api/komik/a?page=2",
"prev": null,
"next": "http://localhost:8000/api/komik/a?page=2"
},
"meta": {
"current_page": 1,
"from": 1,
"last_page": 2,
"links": [
{
"url": null,
"label": "« Previous",
"active": false
},
{
"url": "http://localhost:8000/api/komik/a?page=1",
"label": "1",
"active": true
},
{
"url": "http://localhost:8000/api/komik/a?page=2",
"label": "2",
"active": false
},
{
"url": "http://localhost:8000/api/komik/a?page=2",
"label": "Next »",
"active": false
}
],
"path": "http://localhost:8000/api/komik/a",
"per_page": 2,
"to": 2,
"total": 4
}
}
but when i'll return it using helpers/response
public function search($value)
{
// Query Wildcards and Resources
$result = new KomikCollection(Komik::where('judul', 'like', '%'. $value .'%')->paginate(2));
// send response
return response()->json($result, 200);
}
the meta and link on the json response will be disapppear and return result like this
{
"id": 1,
"title": "Spare me, Great Lord !"
},
{
"id": 2,
"title": "I'm An Evil God"
}
I want the response include the meta and link tags, how do i fix this?
If you want to meta data with response then you must need to add ->response()->getData(true) in collection results.
So your final function looks like :
public function search($value)
{
// Query Wildcards and Resources
$result = new KomikCollection(Komik::where('judul', 'like', '%'. $value .'%')->paginate(2))->response()->getData(true);
// send response
return response()->json($result, 200);
}

categories<-subgaterories->plan how to get categories id wise fetch data laravel

**i want **
$PlanDetails= PalnCategory::select('id','title')->with('Categorys'[subplandetails])->get();
my api response
[
{
"id": 1,
"title": "category 1",
"categorys": [
{
"id": 5,
"subcategor_name": "regular"
},
{
"id": 6,
"subcategor_name": "primum"
}
]
},
{
"id": 2,
"title": "category 2",
"categorys": [
{
"id": 7,
"subcategor_name": "cat2 reg"
}
]
}
]
i want to show
[
{
"id":1,
"title":"category 1",
"categorys":[
{
"id":5,
"subcategor_name":"regular",
"plans":[
{
"id":1,
"name":"plan1"
},
{
"id":2,
"name":"plan2"
}
]
},
{
"id":6,
"subcategor_name":"primum",
"plans":[
{
"id":3,
"name":"plan3"
},
{
"id":4,
"name":"plan4"
}
]
}
]
},
{
"id":2,
"title":"category 2",
"categorys":[
{
"id":7,
"subcategor_name":"cat2 reg",
"plans":[
{
"id":3,
"name":"plan3"
},
{
"id":4,
"name":"plan4"
}
]
}
]
}
]
my model
public function Categorys()
{
return $this->belongsToMany(PlanSucategory::class)->select('id','subcategor_name');
}
public function PlanDetails()
{
return $this->belongsToMany(PlanDetail::class);
}
my controller
$PlanDetail= PalnCategory::select('id','title')->with('Categorys','PlanDetails')->get();
return response()->json($PlanDetail);
here subcategories id same anthor to table categories<-subcategories->plandetails but i want to fetch data categories->subcategories->plandetails
here subcategories id same anthor to table categories<-subcategories->plandetails but i want to fetch data categories->subcategories->plandetailshere subcategories id same anthor to table categories<-subcategories->plandetails but i want to fetch data categories->subcategories->plandetails
I'm not going to modify your query, but instead use a collection, which will transform the data after the get() method.
$PlanDetail = PalnCategory::select('id','title')
->with('Categorys','PlanDetails')
->get()
->groupBy('categorys.0.id')
->values()
->map(function($item){
$sub = collect($item)->map(function($item){
$return = collect($item)->forget(['categorys', 'plan_details'])->all();
$return['plans'] = $item['plan_details'];
return $return;
})->toArray();
$category = $item[0]['categorys'][0];
$category['categorys'] = $sub;
return $category;
});
return response()->json($PlanDetail);
Output :
[
{
"id": 1,
"title": "category 1",
"categorys": [
{
"id": 5,
"subcategor_name": "regular",
"plans": [
{
"id": 6,
"details": "plan1 reg"
}
]
},
{
"id": 6,
"subcategor_name": "primum",
"plans": [
{
"id": 7,
"details": "plan2 reg2"
}
]
}
]
},
{
"id": 2,
"title": "category 2",
"categorys": [
{
"id": 7,
"subcategor_name": "cat2 reg",
"plans": [
{
"id": 8,
"details": "plan1"
}
]
}
]
}
]

how to return a json response based on database relationship

I'm quite new to Laravel,
Let's say I have 2 tables: main_sport and sub_sport. These two tables have a one-to-many relationship. 1 sport can have many sub sports.
I want the following json format
{
"success": "1",
"sports": [
"id": 1,
"name_of_categories": "Popular Sports",
"sub_sports:[
{
"id": 1,
"name_sub_sport_category": "Badminton"
},
{
"id": 2,
"name_sub_sport_category": "Football"
},
{
"id": 3,
"name_sub_sport_category": "Cricket"
},
]
]
"sports":[
"id": 2,
"name_of_categories": "Team Sports",
"sub_sports:[
{
"id": 4,
"name_sub_sport_category": "Badminton"
},
{
"id": 5,
"name_sub_sport_category": "Football"
},
]
]
}
I try for this function and i am getting following result
public function fetch()
{
$query= DB::table('details')
->join('table_sub_sport_category','table_sub_sport_category.id','=','details.sub_id')
->join('table_main_sport_category','table_main_sport_category.id','=','details.main_id')
->select(DB::raw('table_main_sport_category.id as id'),'table_main_sport_category.name_of_categories','table_sub_sport_category.name_sub_sport_category')
->get()
return response()->json(['success' =>'1','data'=>$query]);
}
{
"success": "1",
"data": [
{
"id": 1,
"name_of_categories": "Popular Sports",
"name_sub_sport_category": "Badminton"
},
{
"id": 1,
"name_of_categories": "Popular Sports",
"name_sub_sport_category": "Football"
},
{
"id": 1,
"name_of_categories": "Popular Sports",
"name_sub_sport_category": "Cricket"
},
]
}
Could you help me to get the desired result?
You should define sub_sport in the main sport Model like this:
class Sport extends Model{
public function sub_sport(){
return $this->hasMany(SubSport::class);
}
}
And in your controller you should write this:
$data = Sport::with('sub_sport')->get();
Use below code
$query= DB::table('details')
->join('table_sub_sport_category','table_sub_sport_category.id','=','details.sub_id')
->join('table_main_sport_category','table_main_sport_category.id','=','details.main_id')
->select(DB::raw('table_main_sport_category.id as id'),'table_main_sport_category.name_of_categories','table_sub_sport_category.name_sub_sport_category')
->get()
return Response::json([
'status' => 'error',
'sports' => $query
], 200);

remove data from laravel fractal

I'm using laravel-fractal to transform my data and here is a response
how can I delete data;
I made a search and I realized I need to use a Serializer;
But I just want to remove data for all includes(relations)
{
"data": [
{
"id": 1,
"name": "test name",
"status": null,
"tags": [
"first",
"second"
],
"created_at": "1396/9/3",
"contacts": {
"data": [
{
"value": "test#test.com",
"type": "email",
"icon": "fa fa-email"
}
]
}
},
{
"id": 2,
"name": "name test 2",
"status": null,
"tags": [],
"created_at": "1396/9/3",
"contact": {
"data": []
}
}
]
I found my answer at GitHub. The following answer is copied from thephpleague/fractal on GitHub:
You can write your own serializer for that.
class YourDataSerializer extends ArraySerializer
{
public function collection($resourceKey, array $data)
{
if ($resourceKey) {
return [$resourceKey => $data];
}
return $data;
}
public function item($resourceKey, array $data)
{
if ($resourceKey) {
return [$resourceKey => $data];
}
return $data;
}
}
Register your serializer with manager
$manager = new Manager();
$manager->setSerializer(new YourDataSerializer());
and when you want to have data or anything else you can pass in resourceKey to your Item or Collection as a third param.
$resource = new Collection($folders, new AccountFolderTransformer(), 'data');
use array serializer:
Fractal::create()
->item($item, new MyTransformer())
->serializeWith(new ArraySerializer())

Laravel's Eloquent pivot object

I have defined relation in my model:
public function positions() {
return $this->belongsToMany('Position', 'users_positions')->withPivot('season');
}
Is it possible to display objects with pivot in cleaner way?
For Example:
"positions": [
{
"id": 1,
"name": "A",
"pivot": {
"user_id": 1,
"position_id": 1,
"season": 2014
}
}
],
I would like to get:
"positions": [
{
"id": 1,
"name": "A",
"season": 2014
}
],
Use accessor:
public function getSeasonAttribute()
{
return ($this->pivot) ? $this->pivot->season : null;
}
Then you can access it just like other properties:
$position = $someModel->positions->first();
$position->season;
if you also need it in the toArray/toJson output, then use on you model:
protected $appends = ['season'];

Resources