Reputation: 1244
I'm using Laravel & jQuery
in order to insert
data to a MySQL
table and take back the new id of the new row. The problem is that i get as a response an empty object. I have tried also to print_r
the result in my Controller but i got back a huge array.
Here is some code.
jQuery :
$.ajax({
url: "locations/new",
type: "get", //send it through get method
data:{name:name,description:description},
success: function(response) {
$data = $(response);
console.log($data);
},
error: function() {
console.log("Unable add")
}
});
Controller :
$name= Input::has('name') ? Input::get('name') : null;
$description= Input::has('description') ? Input::get('description') : null;
$add = Location::add($name, $description);
return $add;
and my Model:
public static function add($name,$description){
$location_id = DB::table('locations')->insertGetId(
array('name' => $name, 'description' => $description)
);
Self::get($location_id);
}
public static function get($location_id){
$result = DB::table('locations')->where('location_id',$location_id)
->select(DB::raw('location_id,name'));
$result->get();
return $result;
}
I know that i might have a mistake here. Please except your answers i would like to know the reason of the mistake.
Thanks in advance..
Upvotes: 3
Views: 3623
Reputation: 10346
After co-investigating (@chat), the problem seemed to be in the Query builder.
After adding var_dump($result)
the output was:
Error: Syntax error, unrecognized expression: object(Illuminate\Database\Query\Builder)#248 (27) { ["connection":prot
I suggested removing the DB::raw
function as you can pass fields to the select
function, and from convenient reasons to attach the ->get() function to the same line. So the final query builder code would be:
$result = DB::table('locations')->where('location_id',$location_id)->select('location_id','name')->get();
Which solved the problem.
Update - The Reason
After looking deeper in the source of the framework, I've found out that:
/**
* Set the columns to be selected.
*
* @param array $columns
* @return $this
*/
public function select($columns = array('*'))
{
$this->columns = is_array($columns) ? $columns : func_get_args();
return $this;
}
So the select
function is expecting an array or arguments as columns
, and when db::raw
was in use - it returned a string which conflicted with the expected parameters of the select
function.
Upvotes: 3
Reputation: 13325
This is what your controller should look like
$location = new Location();
$location->name = Input::get('name', null);
$location->description= Input::get('description', null);
$location->save();
return response()->json(location);
Upvotes: 0