Home > other >  Insert Record according to foreign key in laravel 9
Insert Record according to foreign key in laravel 9

Time:09-20

I want To Insert Record According To Foreign Key(project_id) But Can't Inserted.I don't Know what's the problem

Model:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Task extends Model
{
    use HasFactory;
//    protected $fillable = ['project_id'];
    protected $guarded = [];


    public function task(){
        return $this->belongsTo(Project::class);
    }
}

Controller:

<?php

namespace App\Http\Controllers;

use App\Models\Project;
use App\Models\Task;
use Illuminate\Http\Request;

class TaskController extends Controller
{
    //
    public function index(){
        return view('task');
    }


    public function insert(Request $request)
    {
        $validation = $request->validate([
            'title'=>'required',
        ]);




        Task::create($validation);
        return redirect()->back()->with('success','data inserted');
    }
}

Please Guide me How to Insert Record According To Foreign Key(project_id)

CodePudding user response:

First of all if you are not using fillable you must put all the fields 1 by 1 into that table.

Example:

$task = new Task();
$task->title = 'title';
$task->save();

If you want to use Task::create([]); you must declare them into fillable properties all the fields you want to insert in the table.

You could do:

$request->validate([
            'title'=>'required',
        ]);

    Task::create($request->validated());

Don't forget to add the columns in fillable array

CodePudding user response:

You need to specify the foreign key value, unless it's null-able. And as Apollo said, you need to add the column in the fillable array in your model

CodePudding user response:

Rename relation name,

In Task

  public function project(){
        return $this->belongsTo(Project::class);
    }

In Peojct

 public function task(){
        return $this->yourRelation(Project::class); yourRelation -> //hasOne , hasMany
    }

Now when creating task use this code . $project => existed Project Model instance , $project = Project::find(1) // Project::find($request->project_id)

$project->task()->create($request->validated());

When directly creating task you need project_id and it should be fillable in Project Model.

CodePudding user response:

#model

you must use this array in the model, and the pivot table's name must be incorrect.

protected $fillable = [
        'title'
    ];

##controller

    public function insert(Request $request)
    {
        $validation = $request->validate([
            'title'=>'required',
        ]);
        $task=Task::create($request->toArray());
        $task->projects()->sync([project key]);
       }
  • Related