I am facing some problems with PHP Laravel update function. It doesn't update, only insert.
public function post_rate(){
$o = Input::all();
//has user already rated?!
$query = DB::table("ratings")->select("id")->where("user", "=", Auth::user()->id)->where("story_id", "=", $o['story_id'])->get();
foreach ( $query as $d):
$theID = $d->id;
endforeach;
if ( empty($query)): //User hasn't rated!
$z = new Rating();
else:
$z = new Rating($theID); //user has rated, tell which to update
-----------------------------^ that cause the problem!
endif;
$z->story_id = $o['story_id'];
$z->user = Auth::user()->id;
$z->rating = $o['rating'];
$z->save();
echo "OK";
}
It works when no rows founded, but when i will use new Rating(@something) it fails.
the column id in "ratings" table is primary and auto_increment.
In my model i have also set up
public static $key = 'id';
The output "$theID" also contains the correctly ID for the mysql row.
Try: $z = Rating::find($theID)
with ->first()
or ->get()
instead
$z = Rating::find($theID);
or
$z = Rating::where('id', '=', $theID)->first();
Both are equivalent.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With