Example #1
0
 /**
  * store a resource 
  * @param  Request 	$request http request
  * @param  mixed  	$id      id of the resource for updating
  * @return jsend           	 jsend with newly stored source
  */
 function store(Request $request, $id = null)
 {
     ////////////////
     // Load Data  //
     ////////////////
     if ($id) {
         $data = Model::find($id);
         if (!$data) {
             return app()->abort(404);
         }
     } else {
         $data = new Model();
     }
     ///////////////////////////////////
     // Assign posted data to Data    //
     ///////////////////////////////////
     $data->fill($request->input());
     ///////////////////////////////////////////////////////////////////
     // 							Validate data 						 //
     ///////////////////////////////////////////////////////////////////
     # Validate User
     if ($request->input('user_id')) {
         if (!is_scalar($request->input('user_id'))) {
             return response()->json(JSend::fail(['user' => ['Invalid User']])->asArray());
         } else {
             $user = User::find($request->input('user_id'));
             if (!$user) {
                 return response()->json(JSend::fail(['user' => ['Invalid User']])->asArray());
             }
             $data->user_id = $request->input('user_id');
         }
     }
     ///////////////////////////
     // Embeds Other Document //
     ///////////////////////////
     ///////////////////////
     // EMBED IMAGES 	 //
     ///////////////////////
     foreach ($this->request->input('images') as $x) {
         $images[] = new Image($x);
     }
     if (!$data->syncImages($images)) {
         return response()->json(JSend::fail($data->getErrors())->asArray())->setCallback($this->request->input('callback'));
     }
     ///////////////////////
     // EMBED TAGS	 	 //
     ///////////////////////
     foreach ($this->request->input('tags') as $x) {
         $tags[] = new Tag($x);
     }
     if (!$data->syncTags($tags)) {
         return response()->json(JSend::fail($data->getErrors())->asArray())->setCallback($this->request->input('callback'));
     }
     ///////////
     // Store //
     ///////////
     if ($data->save()) {
         return response()->json(JSend::success(['data' => $data])->asArray());
     } else {
         return response()->json(JSend::fail($data->getErrors())->asArray());
     }
 }