Use the following example to create a more powerful driver function.
- We check if the request comes from an AJAX request or not, and we return a response in JSON or a Redirect depending on the case
- Using Try / Catch to capture errors
- Using Log for error log
-
public function store()
{
$data = [
'name' => Input::get('name'),
];
try
{
$result = $this->repository->create($data);
}
catch (Illuminate\Database\QueryException $e)
{
Log::error("YourController@store: register your error", array('created_by' => Auth::user()->id, 'message' => $e->getMessage());
if (!Request::ajax())
{
return Redirect::back()
->with('type_message', "danger")
->with('message', trans('web.error'))
}
else
{
return "{\"result\":\"ko\",\"error\":\"$e->getMessage()\"}";
}
}
if ($result)
{
if (!Request::ajax())
{
Log::info("YourController@store: Created OK", array('created_by' => Auth::user()->id, 'result' => $result->toArray()));
return Redirect::back()
->with('type_message', "success")
->with('message', trans("web.created_ok"));
}
else
{
return "{\"result\":\"ok\",\"id\":\"$result->id\",\"name\":\"$result->name \"}";
}
}
else
{
return "{\"result\":\"ko\",\"error\":\"Hubo un error guardando\"}";
}
}
Example of AJAX request:
$.ajax({
url: "{{ route('my_route')}}",
data: "name="+name+"&_token={{ csrf_token()}}",
dataType: "json",
method: "POST",
success: function(result)
{
if (result['result'] == 'ok')
{
}
else
{
}
},
fail: function(){
},
beforeSend: function(){
}
});
});
Create a route that points to the Store method of your controller, which will serve you both for requests from a form and for AJAX requests:
Route::post('/my_route', array('as' => 'my_route', 'uses' => 'YourController@store'));