Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel First Or New

I seem to be getting the same error when I use UpdateOrNew or FirstOrNew in Laravel, to the best of my knowledge I have implemented the code correctly.

Current Code

    $updateOrCreate = Rating::firstOrNew(
        array(
            'user_id' => Auth::user()->id,
            'video_id' => $_POST['videoId']
            )
    );

    $updateOrCreate->user_id = Auth::user()->id;
    $updateOrCreate->video_id = $_POST['videoId'];
    $updateOrCreate->rating =   $_POST['rating'];

    if($updateOrCreate->save()){
        echo "saved";
    }else{
        echo "failed";
        print_r($_POST);
    };

Error

error: {type:Illuminate\Database\Eloquent\MassAssignmentException, message:user_id,…}
file: "/home/celeb/public_html/dev/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Model.php"
line: 411
message: "user_id"
type: "Illuminate\Database\Eloquent\MassAssignmentException"
like image 997
Brent Avatar asked Nov 30 '22 18:11

Brent


2 Answers

"You may also use the create method to save a new model in a single line. The inserted model instance will be returned to you from the method. However, before doing so, you will need to specify either a fillable or guarded attribute on the model, as all Eloquent models protect against mass-assignment". [See Laravel Documentation on Eloquent Insert, Update, Delete ] (http://laravel.com/docs/5.0/eloquent#insert-update-delete)

That means, only the create method can protect your codes from mass assignment:

/*$user=*/ User::create(array( 'name' => 'Max', 'email' => '[email protected]' ));

When using the create method, you specify the model's name which is User from the example above. This model (usually User.php) is the place where you assign the mass assignable variables:

protected $fillable = ['name', 'email'];

like image 33
MaXi32 Avatar answered Dec 04 '22 00:12

MaXi32


You need to enable mass assignment in your model as such:

class User extends Eloquent {

    protected $fillable = array('first_name', 'last_name', 'email');

}

So any field that can be mass assigned should be in the $fillable variable.

Assigning values without mass assignment:

$user = new User;
$user->id = 3;
$user->name = "Joe";

$user->save();

Assigning values with mass assignment:

$userDetails = array('id' => 3, 'name' => 'Joe');
$user = User::create($userDetails);
like image 163
Joe Avatar answered Dec 03 '22 22:12

Joe