Reputation: 163
I need pass Project Model id as project_id to My Task Model table. this is My TaskController
public function store(Request $request, Project $project)
{
$task = new Task;
$task->task_name = $request->input('name');
$task->body = $request->input('body');
$task->assign = $request->input('status');
$task->priority = $request->input('status');
$task->duedate = date("Y-m-d", strtotime($request->input("date")));
$task->project_id = $project->id;
// This will set the project_id on task and save it
$project->tasks()->save($task);
}
this is My form action route regarding to store task data in projects folder blade file is show.blade.php
<form method="post" action="{{ route('tasks.store') }}">
this is Task Mode
<?php
namespace App;
use App\User;
use App\Auth;
use App\Project;
use Illuminate\Database\Eloquent\Model;
class Task extends Model
{
protected $fillable = ['task_name', 'body', 'assign','priority','duedate','project_id'];
public function scopeProject($query, $id)
{
return $query->where('project_id', $id);
}
public function projects()
{
return $this->belongsTo('App\Project');
}
//
}
this is Project Model
{
protected $fillable = ['project_name','project_notes','project_status','color','group'];
//
public function tasks(){
return $this->hasMany('App\Task');
}
but I got this error massage here
SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'project_id' cannot be null how can fix this problem?
Upvotes: 0
Views: 2689
Reputation: 1529
In your migration file you are not mention that project_id is null. You have to add project_id in this way if you are not
$table->string('project_id')->nullable();
if you not used like that way then you must have to pass project_id as a valid value like 0 or anything but not null. See the error. It says that project_id can not be null. so you can not use null value as project_id.
you said in you database that project_id is not null but send null value thats why you have got this error. Hope you understand.
Upvotes: 1
Reputation: 558
Only set project_id
field to a valid value or zero (If it haven't unique index)
Upvotes: 0
Reputation: 1646
In your store() function you don't give the task a project_id.
So when you save your task it makes the project_id row null. By default this is not allowed for a row. That's why you get this error.
I think adding this line would work:
$task->project_id = $project->id;
You can also make the project_id nullable in your migration. If you do that you allow the project_id to be null. But I don't think that, that is something you want.
Upvotes: 1