I have two tables users
and invoices
. This is the up
function for the users
migration:
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('name')->unique();
$table->string('email')->unique();
$table->string('phone')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->string('comentarii');
$table->rememberToken();
$table->timestamps();
});
}
This is the up
function for the invoices
migration:
public function up()
{
Schema::create('invoices', function (Blueprint $table) {
$table->id();
$table->unsignedInteger('user_id');
$table->foreign('user_id')->refferences('id')->on('users');
$table->integer('InvoiceNumber');
$table->dateTime('date');
$table->string('serviceInvoiced');
$table->timestamps();
});
}
All I am trying to do is to make a one to many relationship as in a user can have multiple invoices.
Here is the User
model:
namespace App\Models;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;
class User extends Authenticatable
{
use HasApiTokens, HasFactory, Notifiable;
/**
* The attributes that are mass assignable.
*
* @var string[]
*/
protected $guarded = [];
/**
* The attributes that should be hidden for serialization.
*
* @var array
*/
protected $hidden = [
'password',
'remember_token',
];
/**
* The attributes that should be cast.
*
* @var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
public function getInvoices()
{
return $this->hasMany(Invoice::class);
}
}
Here is the Invoice
model:
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Invoice extends Model
{
use HasFactory;
protected $guarded=[];
public function getUsers()
{
return $this->belongsTo(User::class);
}
}
What am I doing wrong? I watched multiple tutorials already. Here are the errors that im getting:
CodePudding user response:
The columns need to be of the same type. id()
is an alias of bigIncrements()
, so
$table->unsignedInteger('user_id');
should be
$table->unsignedBigInteger('user_id');
Also note: it's ->references('id')
, not ->refferences('id')
More on Available Column Types
CodePudding user response:
you have tow issues:
1- you have a typo in your migration statement
2- $this->id()
make unsignedBigInteger
so user_id
should be unsignedBigInteger
alter you migration lines to this:
$table->unsignedBigInteger('user_id');
$table->foreign('user_id')->references('id')->on('users'); //references not refferences