Relationship ilişkili kullandığım verileri json verisi olarak nasıl döndürebilirim?
//MODEL_RESTORANT
public function categories()
{
return $this->hasMany('App\Categories','restorant_id','id');
}
//MODEL_CATEGORIES
public function items()
{
return $this->hasMany('App\Items','category_id','id');
}
//MODEL_ITEMS
public function category()
{
return $this->belongsTo('App\Categories');
}
public function item($itemid)
{
return $this->hasMany('App\Items','category_id','id')->where('items.id',$itemid);
}
//CONTROLLER
$categories = $restorant->categories;
return view('items.index', ['categories' => auth()->user()->$categories->reverse()]);
//BLADE
@foreach($categories as $category)
{{$category->name}}
{{$category->photo}}
@foreach($category->items as $item)
{{$item->name}}
{{$item->description}}
{{$item->price}}
@endforeach
@endforeach
Şu anda ki sistem böyle çalışıyor view'de sıkıntısız olarak Kategori adı ve altında item adları aşağı doğru sıralanıyor:
Örn:
Kategori 1
item 1
item 2
item 3
Kategori 2
item 1
item 2
Api'dan verileri alıp başka bir yerde aynı şekilde kullanmam gerekiyor, fakat bir türlü uygun json verisini üretemedim cliente gönderilebilicek.
$dene = [];
$categories = $restorant->categories;
foreach ($categories as $category){
$dene['id'] = $category->id;
$dene['name'] = $category->name;
foreach ($category->items as $key => $item){
$dene['items']['name'] = $item->name;
$dene['items']['description'] = $item->description;
$dene['items']['price'] = $item->price;
}
}
return response()->json([
'data' => $dene,
'status' => true,
'errMsg' => ''
]);`
@BAŞARISIZ
$restorant = Restorant::where(['id' => $id, 'active' => 1])->with(['categories'])->first();
$items = [];
if($restorant){
if($restorant->categories){
foreach($restorant->categories as $key => $value){
$theItem=$value->items->toArray();
foreach ($theItem as $key => &$ivvalue) {
$ivvalue['category_name']=$value->name;
}
array_push($items,$theItem);
}
return response()->json([
'data' => $items,
'status' => true,
'errMsg' => ''
]);
}else{
return response()->json([
'status' => false,
'errMsg' => 'Restorant categories not found!'
]);
}
}else{
return response()->json([
'status' => false,
'errMsg' => 'Restorant not found!'
]);
}
@BU DA CLIENT'İN BLADE TARAFINDA KARMA KARIŞIK BİR HALE DÖNÜŞTÜ VE DÜZGÜN ÇALIŞTIRAMADIM
Umarım derdimi anlatabilmişimdir. Bu konuda yardımcı olursanız çok sevinirim.