Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel Eloquent doesn't update only inserting

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.

like image 544
kim larsen Avatar asked Jan 13 '23 03:01

kim larsen


2 Answers

Try: $z = Rating::find($theID) with ->first() or ->get() instead

like image 127
Rob W Avatar answered Jan 17 '23 17:01

Rob W


$z = Rating::find($theID);

or

$z = Rating::where('id', '=', $theID)->first();

Both are equivalent.

like image 40
coffe4u Avatar answered Jan 17 '23 18:01

coffe4u