Answer the question
In order to leave comments, you need to log in
How to set up User Model relationships in Laravel 5.4?
There are two models. User (derived from make:auth ) and Ad . The Ad model inherits Model , and the User model inherits Authenticatable .
As a result, when I try to assign relationships between models, I get an error:
General error: 1364 Field 'user_id' doesn't have a default value
public function user()
{
return $this->belongsTo('App\User');
}
public function ads()
{
return $this->hasMany('App\Ad');
}
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
public function ads()
{
return $this->hasMany('App\Ad');
}
use Notifiable;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name', 'email', 'password', 'category_id', 'user_id'
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password', 'remember_token',
];
}
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Ad extends Model
{
public function category()
{
return $this->belongsTo('App\Category');
}
public function user()
{
return $this->belongsTo('App\User');
}
public function adimages()
{
return $this->hasMany('App\AdImage');
}
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question