Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 5.2 Eloquent create() method shows foreign key exception but save() doesn't show any error

Here is the situation:

I have two tables users and projects. Users table has one to many relation with projects table. When I try to insert data in projects table by using Model::create() method, it shows foreign key constraint error. But when I create an instance of Project model and set attribute and use $modelObject->save() method it works. Below is the code

ProjectsController.php (Controller) (function: postStart()) -

public function postStart(Request $request)
{
    $input = $request->input();

    $project = Project::create(array(
        'title' => $input['title'],
        'main_category_id' => $input['category'],
        'user_id' => Auth::id(),
        'slug' => Helper::slug($input['title']),
    ));

    $project['slug'] = Helper::slug($input['title'], $project->id);
    $project->save();

    return redirect('project/'.$project->slug.'/edit');
}

Project.php (model)

class Project extends Model
{
    protected $fillable = ['user_id', 'main_category_id', 'sub_category_id', 'title', 'slug', 'description', 'project_location', 'project_url', 'project_image', 'type', 'min_bid_amount'];

    public static $updatable = ['user_id' => "", 'main_category_id' => "", 'sub_category_id' => "", 'title' => "", 'slug' => "", 'description' => "", 'project_location' => "", 'project_url' => "", 'project_image' => "", 'type' => "", 'min_bid_amount' => ""];

    public function user() {
        return $this->belongsTo('User');
    }
}

And Here is the error

QueryException in Connection.php line 673: SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (kickstarter.projects, CONSTRAINT projects_user_id_foreign FOREIGN KEY (user_id) REFERENCES users (id)) (SQL: insert into projects (updated_at, created_at) values (2016-05-24 13:00:27, 2016-05-24 13:00:27))

But when I insert using $modelObject->save() method it works. I do not understand what is the problem. It would be very helpful if I found a solution.

like image 776
Jitender Singla Avatar asked May 24 '16 13:05

Jitender Singla


1 Answers

Are you sure that you provided all needed information? If you will check create() function, you will see:

public static function create(array $attributes = [])
{
    $model = new static($attributes);

    $model->save();

    return $model;
}

So create method also use save method. You can see from your exception, that you don't set any value for fields. As result - your problem either in $attributes or in constructor in your class. Because $attributes seems like have values and fields are fillable - you need go further into constructor. Also there is an error in relation

public function user() {
    return $this->belongsTo('User', 'id');
}

The method should return $this->belongsTo('User', 'user_id') or $this->belongsTo('User')

UPD:

As we understand from commetns, constructor was re-implemented and as result - attributes assignment doesn't work. To fix this issue you need just call parent constructor method and add new logic, that you need:

public function __construct(array $attributes = [])
{
    parent::__construct($attributes);
    // some additional code
}
like image 57
f0rtis Avatar answered Nov 14 '22 23:11

f0rtis