Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

ilarioengler's avatar

Integrity constraint violation

I have 3 models: Priority, Task and User

Priority

  • can be assigned to many tasks
  • belongs to one user

Code ...

class Priority extends Model
{
    protected $fillable = ['name', 'hexcolorcode'];

    protected $casts = [
        'user_id' => 'int',
    ];

    public function task()
    {
        return $this->hasMany(Task::class);
    }

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

Task

  • has one priority assigned
  • belongs to one user

Code ...

class Task extends Model
{
    protected $fillable = ['name'];

    protected $casts = [
        'user_id' => 'int',
    ];

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

    public function priority()
    {
        return $this->hasOne(Priority::class);
    }
}

User

  • can have many tasks
  • can have many priorities

Code ...

class User extends Authenticatable
{

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

    protected $hidden = [
        'password', 'remember_token',
    ];

    public function tasks()
    {
        return $this->hasMany(Task::class);
    }

    public function priorities()
    {
        return $this->hasMany(Priority::class);
    }
}

TaskController

class TaskController extends Controller
{
    protected $tasks;

    private $priorities;

    public function __construct(TaskRepository $tasks, PriorityRepository $priorities)
    {
        $this->middleware('auth');
        $this->tasks = $tasks;
        $this->priorities = $priorities;
    }

    public function index(Request $request)
    {
        return view('tasks.index', [
            'tasks' => $this->tasks->forUser($request->user()),
            'priorities' => $this->priorities->forUser($request->user())
        ]);
    }

    public function store(Request $request)
    {
        $this->validate($request, [
            'name' => 'required|max:255',
            'description' => 'required',
            'priority' => 'required'
        ]);

        $request->user()->tasks()->create([
            'name' => $request->name,
            'description' => $request->description,
            'priority_id' => $request->priority
        ]);

        return redirect('/tasks');
    }

    public function edit(Task $task)
    {
        $this->authorize('edit', $task);

        return view('tasks.edit', compact('task'));
    }

    public function update(Request $request, Task $task)
    {
        $this->validate($request, [
            'name' => 'required|max:255',
        ]);

        $task->update($request->all());
        return redirect('/tasks');
    }

    public function destroy(Request $request, Task $task)
    {
        $this->authorize('destroy', $task);

        $task->delete();

        return redirect('/tasks');
    }
}

Error

Now when I want to store a task it gives me following error:

SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (tasks.tasks, CONSTRAINT tasks_priority_id_foreign FOREIGN KEY (priority_id) REFERENCES priorities (id)) (SQL: insert into tasks (name, user_id, updated_at, created_at) values (test task, 1, 2016-05-01 14:11:21, 2016-05-01 14:11:21))

Is it possible with this construct or do I have to use Polymorphic Relations between priority table and tasks table?

My Tables

Database Model Picture: http://picpaste.de/mysql-kBH4tO5T.PNG

class CreatePrioritiesTable extends Migration
{

    public function up()
    {
        Schema::create('priorities', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('user_id')->unsigned();
            $table->char('name');
            $table->char('hexcolorcode', 7);
            $table->timestamps();
            $table->foreign('user_id')->references('id')->on('users');
        });
    }
}


class CreateTasksTable extends Migration
{

    public function up()
    {
        Schema::create('tasks', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('user_id')->unsigned();
            $table->string('name');
            $table->text('description');
            $table->integer('priority_id')->unsigned();
            $table->timestamps();
            $table->foreign('priority_id')->references('id')->on('priorities');
            $table->foreign('user_id')->references('id')->on('users');
        });
    }
}

UPDATE

PriorityController

class PriorityController extends Controller
{

    protected $priorities;

    public function __construct(PriorityRepository $priorities)
    {
        $this->middleware('auth');
        $this->priorities = $priorities;
    }

    public function index(Request $request)
    {
        return view('priority.index', [
            'priorities' => $this->priorities->forUser($request->user()),
        ]);
    }

    public function store(Request $request)
    {
        $this->validate($request, [
            'name' => 'required|max:255',
            'hexcolorcode' => 'required|max:7'
        ]);

        $request->user()->priorities()->create($request->all());

        return redirect('/priorities');
    }

    public function edit(Priority $priority)
    {
        $this->authorize('edit', $priority);

        return view('priority.edit', compact('priority'));
    }

    public function update(Request $request, Priority $priority)
    {
        $this->validate($request, [
            'name' => 'required|max:255',
            'hexcolorcode' => 'required|max:7'
        ]);

        $priority->update($request->all());
        return redirect('/priorities');
    }

    public function destroy(Request $request, Priority $priority)
    {
        $this->authorize('destroy', $priority);

        $priority->delete();

        return redirect('/priorities');
    }
}
0 likes
11 replies
willvincent's avatar

priority on task shouldn't be hasOne, it should be a belongsTo:

class Task extends Model
{
    protected $fillable = ['name'];

    protected $casts = [
        'user_id' => 'int',
    ];

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

    public function priority()
    {
        return $this->belongsTo(Priority::class);
    }
}
willvincent's avatar

If you look at your SQL error, it's complaining because you're not setting the priority_id.

If you change this,

    $request->user()->tasks()->create([
        'name' => $request->name,
        'priority' => $request->priority
    ]);

to this:

    $request->user()->tasks()->create([
        'name' => $request->name,
        'priority_id' => $request->priority
    ]);

does that help?

ilarioengler's avatar

@willvincent no, but I noticed that the priority id isn't set in the sql statement:

SQL: insert into tasks (name, user_id, updated_at, created_at) values (test task, 1, 2016-05-01 14:11:21, 2016-05-01 14:11:21)

But if you open my link where the DB Model is shown, you see that the tasks table contains a priority_id column.

d3xt3r's avatar

but I noticed that the priority id isn't set in the sql statement

How do you except the priority_id to be set without explicitly setting it. Either use methods meant for relationships, or set the foreign key yourself.

ilarioengler's avatar

@d3xt3r but the other fields are set automatically name, user_id, updated_at, created_at. Why is priority_id not set?

Give a look at my post I updated it!

d3xt3r's avatar

fields are set automatically

How???

ilarioengler's avatar

@d3xt3r

$request->user()->tasks()->create([
    'name' => $request->name,
    'description' => $request->description,
    'priority_id' => $request->priority
]);

How would you do it? Do you see any mistakes I do?

d3xt3r's avatar
d3xt3r
Best Answer
Level 29

Couple of things.

1> dd($request->priority); // What do you see

2> In Task model, is priority_id in the fillable list ? If not then, it wont be added to sql while using create();

1 like
ilarioengler's avatar

1>"The priorityname I entered" -> have to get the id based on the name

2>no that was the problem

I had an understanding problem, because user_id is also assigned but it isn't specified in fillable array. But because I say $request->user->tasks->create(); it is assigned from the framework, but priority_id is assigned through the user so, it is mass assigned and need to be specified in the fillable array.

Thank you very much. I got some new understanding tonight! I'm new to laravel framework ;)

willvincent's avatar

why not hasOne?

Because you have the foreign key in the table... it's a belongsTo, not a hasOne

1 like

Please or to participate in this conversation.