0👍
Solution will be to define relation hasOne like
public function parent()
{
return $this->hasOne(Category::class,'id','parent_id');
}
And then you can define resource, where you can claim parent’s title using defined relation like below
$this->parent->title
Create you resource using command
php artisan make:resource CategoryResource
Then in your controller you should use resource
use App\Http\Resources\CategoryResource;
and within controller’s action provide response like
$categories = Category::paginate(15);
return CategoryResource::collection($results); // instead of response()->json($categories , 200);
And example how your resource should look like
<?php
namespace App\Http\Resources;
use Illuminate\Http\Resources\Json\JsonResource;
class CategoryResource extends JsonResource
{
/**
* Transform the resource into an array.
*
* @param \Illuminate\Http\Request $request
* @return array
*/
public function toArray($request)
{
return [
'id' => $this->id,
'title' => $this->title,
'parent_id' => $this->parent_id,
'parent_title' => $this->parent->title,
...
];
}
}
Info about resources you can find https://laravel.com/docs/5.8/eloquent-resources
0👍
This is code of controller
public function index()
{
$result = ['success' => true];
$category = Category::paginate(15);
$result['category'] = $category->items();
$result['pagination']['currentPage'] = $category->currentPage();
$result['pagination']['total'] = $category->total();
$result['pagination']['perPage'] = $category->perPage();
return response()->json($result, 200);
}
And here is how I want it to be
I think render function adn array processing must be at the Vue Component
This is my Category model code
public function products()
{
return $this->hasMany('App/Products');
}
public function parent()
{
return $this->hasOne(Category::class,'id','parent_id');
}
- [Vuejs]-VueX Not detecting change
- [Vuejs]-Connexion refused and CrashLoopBackOff Running Loop for Container with Docker GraphQl
Source:stackexchange.com