If you want this to work you should create a many to many relationship.
Starting off your database should look something like this:
This way your products and categories are linked properly and if you want to add a new category to a product or the other way around you can just add the ids of both the category and the product to the category_product table.
Then for your relation methods, in your Product.php (model) you will get this relation method:
/**
* @return BelongsToMany
*/
public function categories(): BelongsToMany
{
return $this->belongsToMany(Category::class);
}
And in your Category.php (model):
/**
* @return BelongsToMany
*/
public function products(): BelongsToMany
{
return $this->belongsToMany(Product::class);
}
You can now get all categories of a product by using:
$product = Product::first();
$product->categories;
Just for some extra information. You can use your model to store the relations.
For example you would like to add category 1, 2, 3 to the product.
You can simply do:
$product = Product::first();
$product->categories()->sync([1, 2, 3]);