There are two models. User (resulting from make: auth ) and Ad . The Ad model inherits the Model , and the User model inherits the Authenticatable .

As a result, when I try to assign relationships between models, I get the error:

General error: 1364 Field 'user_id' doesn't have a default value

Ad model has the function:

public function user() { return $this->belongsTo('App\User'); } 

The User model has the function:

 public function ads() { return $this->hasMany('App\Ad'); } 

What is the problem and how to solve?

  • If the conversation comes about relationships, then you should write about them - describe the fields of the tables, write how you assign them. - xEdelweiss
  • Maybe your table is no longer empty and there are empty user_id fields, or are they not empty but with values ​​that are not in user_id? - Orange_shadow

1 answer 1

Perhaps you should create in the ads table, user_id int field and write ad user to user_id when creating ad

  ADS table id | int slug | string name | string content | text user_id | int 

Adcontroller

 public function add(Request $request) { $this->validate($request, ['slug' => 'required|alpha|unique:ads', 'name' => 'required', 'content' => 'required']); $Ad = new Ad; $Ad->slug = $request->slug; $Ad->name = $request->name; $Ad->content = $request->content; $Ad->user_id = auth()->user()->id; $Ad->save(); return redirect()->back(); }