Level 3
Is $request->cats an array of Cat IDs? sync() wants to accept an array of model ids that you want to associate:
// if $request->cats equals something like [1,3,4]
$product->cats()->sync($request->cats);
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
Good day. May I please be assisted. I would like to save products with the category. I have a Product Model and Controller and same with Cats. So far I am able to create categories and they are stored in my db. I am also able to create products but when I select a category it does not display the category..
Here is my model and controller
class Product extends Model
{
protected $fillable=['name','description','title','image','price'];
public function cats()
{
//
return $this->belongsToMany('App\Cat');
}
}
public function create()
{
$cats = Cat::all();
return view('admin.product.create',compact('cats'));
}
public function store(Request $request)
{
$this->validate($request,[
'name'=>'required',
'description'=>'required',
'price'=>'required',
'image'=>'image|mimes:png,jpg,jpeg|max:10000'
]);
$product = new Product();
$product ->name = $request->input('name');
$product ->title = $request->input('title');
$product ->description = $request->input('description');
$product ->price = $request->input('price');
$product ->image=$request->input('image');
if($request->hasFile('image')) {
$file = Input::file('image');
//getting timestamp
$timestamp = str_replace([' ', ':'], '-', Carbon::now()->toDateTimeString());
$name = $timestamp. '-' .$file->getClientOriginalName();
$product->image = $name;
$file->move(public_path().'/images/', $name);
}
$product ->save();
$product->cats()->sync($request->cats, false);
Session::flash('flash_message', 'Service successfully added!');
return redirect()->back()->with('success', 'Service Successfully Added');
}
Please or to participate in this conversation.