public function store(Request $request) { $categories = $request->input('category'); $name = $request->input('name'); $duplicate = Products::where('name', $name)->first(); if ($duplicate) { return redirect('/product/create')->withErrors('The name already exists'); } $description = $request->input('description'); $price = $request->input('price'); $user_id = $request->user()->id; $product = new Products(); $product->name = $name; $product->description = $description; $product->price = $price; $product->quantity = $request->input('quantity'); $product->author_id = $user_id; $product->slug = str_slug($request->input('name')); $product->active = 1; if (Input::file('image') != null) { $destinationPath = 'images/catalog'; // upload path $extension = Input::file('image')->getClientOriginalExtension(); // getting image extension $fileName = rand(11111, 99999) . '.' . $extension; // renameing image $product->image = $fileName; Input::file('image')->move($destinationPath, $fileName); // uploading file to given path } $product->save(); if ($categories) { foreach ($categories as $category) { $category = Categories::where('title', $category)->first(); $product->categories()->attach($category->id); } } return redirect('/')->withMessage('New product created'); }