I want to return a collection of posts, based on if a single value exists in an array stored in the table.
In my posts table, I have regular column names like 'title', 'body', and 'slug'. I am managing multiple sites using the same table, so I have an additional column name of 'site_ids'. When a user creates a post, they select what sites they want it published on and it stores the site id's as an array (eg. [1,2])
-----------------------------------------------
| Title | Site_ids | Slug |
-----------------------------------------------
| Test Title |[1,2,3] |test-title |
-----------------------------------------------
| Another Title |[1,6] |another-title |
-----------------------------------------------
Now I am creating an API to return all posts with the site_id of 1. How can this be achieved? Here is my current code in my PostController
API ROUTE
Route::get('/{site_id}/posts','PostController@index')->name('Show Posts');
Code:
public function index($site_id)
{
// Return all posts by id
$posts = Post::whereIn('sites', $site_id)->get();
return new PostCollection($posts);
}
I am getting this error message
Invalid argument supplied for foreach()
What am I doing wrong here?
foreach()in this context? IsPostCollectiona wrapper for aview()?whereIn()converted the second param to an array if it wasn't one, but the answers below seem to be correct to handle that. Does that query work though? I wouldn't think that storing literal[1, 2]would work withwhereIn()...->where("sites", "LIKE", "%".$site_id."%");to handle a wildcard text search (loosely matching[1, 2]to1, etc), but that's inefficient and not the best approach.