John Davidson

php - Insert Record according to foreign key in laravel 9

0 comments
Message:


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)



My Answer:
In order to insert a record with a foreign key (project_id) in Laravel, you need to make sure that you are passing the project_id along with the other fields when creating a new Task record.

Here's how you can modify your insert method in the TaskController to include the project_id:

php
public function insert(Request $request)
{
$validation = $request->validate([
'title'=>'required',
'project_id'=>'required', // make sure project_id is required
]);

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


In your form where you are submitting the data, make sure to include a hidden input field for the project_id. For example:

html

@csrf






Make sure to replace `$project_id` with the actual project_id value that you want to associate with the Task record.

This way, when you submit the form, the project_id will be included in the request data and the Task record will be created with the correct foreign key.

Rate this post

3 of 5 based on 8049 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us