1

CategoryApiController.php

    public function posts($id){<br>
        $category_data = Category::find($id);        
        $posts=$category_data->posts();
}



Category.php (Model)

 public function posts(){
        return Post::whereJsonContains('category_id',$this->attributes['id'])->get();



I am trying to get the Posts for Perticular Category which is stored in Category_id as JSON. If I replace $this->attributes['id'] with '3' which is a static value, I get the data m looking for, but I want it to be dynamic. However $this->attributes['id'] ll fetch the category id for ex (3) successfully, but it's not accepting as an argument and returns an Empty Array.

Here is my table structure:

enter image description here

Please Help Me Out

1
  • 1
    Hi and welcome. You might want to revisit your post and work a bit on the markup as currently it is very hard to read due formatting and typos. A good post might result in more answers than in its current state. From what I see Im wondering what you tried to make it work? Commented Jul 15, 2020 at 10:29

1 Answer 1

2

You have a few problems.

  1. You probably forgot to add array casting.

https://laravel.com/docs/7.x/eloquent-mutators#array-and-json-casting.

When you add this, you should get something like this in you:

// Category.php

protected $casts = [
     'category_ids' => 'array'
];


// CategoryApiController@posts

$model->update(['category_ids' => [1, 2, 3]);
  1. The second problem is the data types. Your array stores strings and you pass a number, so it does not work. Notice in point one I showed you how to save in integer. So if you save in integer, your code will work without changing this line.

Post::whereJsonContains('category_id', 1) // int

Post::whereJsonContains('category_id', '1') // string

e.g. whereJsonContains('category_id', (string)$this->attributes['id']) // pass string

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.