'SQLSTATE[HY000]: General error: 1364 Field 'agent_id' doesn't have a default value
I am getting errors because of the foreign key field. I have two Models ( Agent, Post ). I cannot get the user's primary key to be saved as a foreign key in the posts table. I can insert the data manually, and it links with the parent table, but when the user inserts from the form in view, it gives me that error any help?
Agent
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Agent extends Model
{
use HasFactory;
public function posts(){
return $this->hasMany(Post::class);
}
}
Post
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
use HasFactory;
public function user(){
return $this->belongsTo(Agent::class);
}
}
And here is my method in the controller to save the data.
public function savepost(Request $request)
{
$post = new Post;
$post->title = $request->title;
$post->description = $request->description;
$post->type = $request->type;
$saved = $post->save();
if ($saved) {
return back()->with('success', 'New post has been added successfuly');
} else {
return back()->with('fail', 'Something went wrong , try again later');
}
}
Solution 1:[1]
in my think, Post model should have agent_id and when create new Post, agent_id is required with current user->id. so it seems to be added agent_id in new Post object.
...
use Auth;
...
public function savepost(Request $request){
$post = new Post ;
$post->title = $request->title ;
$post->description = $request->description ;
$post->type = $request->type;
$post->agent_id = Auth::user()->id;
$saved = $post->save();
if($saved){
return back()->with('success','New post has been added successfuly');
}else{
return back()->with('fail' , 'Something went wrong , try again later');
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Brain Hong |
