Example #1
0
 public function StoreGame(Request $request, $info)
 {
     // get the genres
     $genres = str_getcsv($request->genre);
     foreach ($genres as $key => $genre) {
         $genres[$key] = trim($genre);
     }
     // create product record
     $product = new Product($request->all());
     // use database transaction to save the records
     DB::transaction(function () use($product, $info, $genres) {
         // save the product record
         $product->save();
         // set the product id of the details record
         $info->product_id = $product->id;
         if (filter_var($info->poster, FILTER_VALIDATE_URL) !== false) {
             // download the poster
             if (!file_exists('/img/games/' . $info->product_id . '.jpg')) {
                 $buffer = file_get_contents($info->poster);
                 $file = fopen(public_path() . '/img/games/' . $info->product_id . '.jpg', 'w');
                 fwrite($file, $buffer);
                 fclose($file);
             }
             // set the poster url
             $info->poster = '/img/games/' . $info->product_id . '.jpg';
         }
         // save the details record
         $info->save();
         // add the genres
         foreach ($genres as $genre) {
             // if genre does not exist create it
             $record = Genre::where('name', $genre)->first();
             if ($record === null) {
                 $record = Genre::create(['name' => $genre]);
                 $product->genres()->attach([$record->id]);
             } else {
                 $product->genres()->attach([$record->id]);
             }
         }
     });
 }