Home > Enterprise >  write category name with model after laravel post post registration
write category name with model after laravel post post registration

Time:06-30

I have 2 tables and my 1st table is Category 2 My Table is Posts, While I have a category, When I want to save a post, it is added as "category_id" in the post. but, what I want to do is $post->save(); after saying return response()->json([ 'data' =>$post]); I return. but what I want is to return the name of the category instead of the category_id.

While recording, I want to know the name of the post category recorded between the two models.

The content of my category and page models is what I need to write in the empty model

public function store(Request $request)
    {
        $request->validate([
            'title' => 'required|max:255',
            'image' => 'required|mimes:jpg,jpeg,png|max:8192',
            'language' => 'required'
        ]);
$page = new Page;
$page->title = $request->title;
                $page->slug = $request->slug;
                $page->content = $request->contents;
                $page->category_id = $request->cat_id;
                $page->language = $request->language;
$page->save();
return response()->json([
                    'data' => $page,
                    'success' => 'File uploaded successfully.']);

CodePudding user response:

Laravel can automatically serialize models, so ensure you have a relationship, load it into the model and it will be added to your JSON response automatically.

class Page extends Model {
   public function category()
   {
       return $this->belongsTo(Category::class);
   }
}

Using ->load() to lazy load the relationship, if similar has to be done in a query use ->with() which is the eager loading approach.

...

$page->save();
$page->load('category');

return response()->json([
    'data' => $page,
    'success' => 'File uploaded successfully.',
]);

This will add the category as a relationship, but this is the best practice instead of adding the name in a more hard coded way.

Also one of the down sides of filling relationship ids as a property or with fill(). Is that it circumvented Laravels relationship logic, if you instead save the category relationship on the relationship function. It will have loaded the category and work, in the same manner as above.

$page->title = $request->title;
$page->slug = $request->slug;
$page->content = $request->contents;
$page->language = $request->language;

$page->category()->associate(Category::find($request->cat_id));

$page->save();
  • Related