I have a custom User model in laravel. But I get errors when relationships with the User model. I couldn't find a similar problem on the internet. I have no idea what to do.
There was no User model before. I was using a model called Account and it was fine. But I updated the model name to User to use laravel's own Auth system.
Error:
Symfony\Component\ErrorHandler\Error\FatalError
Class Illuminate\Database\Eloquent\Relations\BelongsTo contains 6 abstract methods and must therefore be declared abstract or implement the remaining methods (Illuminate\Contracts\Auth\Authenticatable::getAuthIdentifierName, Illuminate\Contracts\Auth\Authenticatable::getAuthIdentifier, Illuminate\Contracts\Auth\Authenticatable::getAuthPassword, ...)
\vendor\laravel\framework\src\Illuminate\Database\Eloquent\Relations\BelongsTo.php:12
class BelongsTo extends Relation implements \Illuminate\Contracts\Auth\Authenticatable {
My User model
<?php
namespace App\Models;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Relations\HasMany;
class User extends Authenticatable {
use HasFactory;
/**
* The attributes that are mass assignable.
*
* #var string[]
*/
protected $fillable = [
'full_name',
'email',
'password',
];
/**
* The attributes that should be hidden for serialization.
*
* #var string[]
*/
protected $hidden = [
'password',
];
/**
* Get the blog posts for the user.
* #return HasMany
*/
public function posts(): HasMany {
return $this->hasMany(BlogPost::class, 'id', 'author_id');
}
}
BlogPost model
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
class BlogPost extends Model {
use HasFactory;
/**
* The attributes that are mass assignable.
*
* #var string[]
*/
protected $fillable = [
'author_id',
'thumbnail_id',
'title',
'slug',
'content',
'description',
'views',
];
/**
* Get the author for the blog post.
* #return BelongsTo
*/
public function author(): BelongsTo {
return $this->belongsTo(User::class, 'author_id', 'id');
}
}
users table migration:
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateUsersTable extends Migration {
/**
* Run the migrations.
*
* #return void
*/
public function up() {
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('full_name', 64);
$table->string('email', 64)->unique();
$table->string('password');
$table->softDeletes();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down() {
Schema::dropIfExists('users');
}
}
Try adding the Authorizable Trait to the User Model. Don't forget to add the use in too
use Illuminate\Foundation\Auth\Access\Authorizable;
class User extends Authenticatable
{
use Notifiable, Authorizable;
Related
I just started to learn Laravel and I have a problem with seeding the database with proper relationships.
I tried to create four tables which are: 'Users','Projekts','Posts','Projekt_User_Pivots'.
The idea is that every Projekt can have multiple users, every user can have multiple projekts and posts.
So I want to show only the posts within a project, from the users that belong to the project.
I tried to seed the database with seeders and factories but I can't achieve the relationship of primarykeys via the factories I want to use. In my solution I just need to run the seeding as often until it works what is realy dumb. I would appreciate some help.
Here are all Models:
Post.php:
<?php
namespace App\Models;
use App\Models\User;
use App\Models\Projekt;
use Illuminate\Database\Eloquent\Model;
use SebastianBergmann\CodeUnit\FunctionUnit;
use Illuminate\Database\Eloquent\Factories\HasFactory;
class Post extends Model
{
use HasFactory;
public function user()
{
return $this->belongsTo(User::class);
}
}
Projekt.php:
<?php
namespace App\Models;
use App\Models\Post;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Factories\HasFactory;
class Projekt extends Model
{
use HasFactory;
public function user()
{
return $this->belongsTo(User::class);
}
public function projektuserpivot()
{
return $this->hasMany(ProjektUserPivot::class);
}
}
ProjektUserPivot.php:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class ProjektUserPivot extends Model
{
use HasFactory;
protected $primaryKey = ['user_id', 'projekt_id'];
public $incrementing = false;
public function user()
{
return $this->belongsTo(User::class);
}
public function projekt()
{
return $this->belongsTo(Projekt::class);
}
}
User.php:
<?php
namespace App\Models;
// use Illuminate\Contracts\Auth\MustVerifyEmail;
use App\Models\Post;
use App\Models\Projekt;
use Laravel\Sanctum\HasApiTokens;
use Illuminate\Notifications\Notifiable;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use HasApiTokens, HasFactory, Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array<int, string>
*/
protected $fillable = [
'name',
'email',
'password',
];
/**
* The attributes that should be hidden for serialization.
*
* #var array<int, string>
*/
protected $hidden = [
'password',
'remember_token',
];
/**
* The attributes that should be cast.
*
* #var array<string, string>
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
public function post()
{
return $this->hasMany(Post::class);
}
public function projekt()
{
return $this->hasMany(Projekt::class);
}
public function projektuserpivot()
{
return $this->hasMany(ProjektUserPivot::class);
}
}
Here are all Factories:
PostFactory.php:
<?php
namespace Database\Factories;
use Illuminate\Database\Eloquent\Factories\Factory;
use Spatie\LaravelIgnition\Support\Composer\FakeComposer;
/**
* #extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\Post>
*/
class PostFactory extends Factory
{
/**
* Define the model's default state.
*
* #return array<string, mixed>
*/
public function definition()
{
return [
'user_id' => $this->faker->numberBetween(0,999),
'title' => $this->faker->realTextBetween(10, 50),
'body' => $this->faker->realTextBetween(800, 1400),
];
}
}
ProjektFactory.php:
<?php
namespace Database\Factories;
use Illuminate\Database\Eloquent\Factories\Factory;
/**
* #extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\Projekt>
*/
class ProjektFactory extends Factory
{
/**
* Define the model's default state.
*
* #return array<string, mixed>
*/
public function definition()
{
return [
'name' => $this->faker->realTextBetween(10, 20),
'user_id' => $this->faker->numberBetween(1,999),
];
}
}
ProjektUserPivotFactory.php:
<?php
namespace Database\Factories;
use Illuminate\Database\Eloquent\Factories\Factory;
/**
* #extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\ProjektUserPivot>
*/
class ProjektUserPivotFactory extends Factory
{
/**
* Define the model's default state.
*
* #return array<string, mixed>
*/
public function definition()
{
return [
'user_id' => $this->faker->numberBetween(1,999),
'projekt_id' => $this->faker->numberBetween(1,20),
];
}
}
UserFactory.php:
<?php
namespace Database\Factories;
use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Str;
/**
* #extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\User>
*/
class UserFactory extends Factory
{
/**
* Define the model's default state.
*
* #return array<string, mixed>
*/
public function definition()
{
return [
'name' => fake()->name(),
'email' => fake()->unique()->safeEmail(),
'email_verified_at' => now(),
'password' => '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', // password
'remember_token' => Str::random(10),
];
}
/**
* Indicate that the model's email address should be unverified.
*
* #return static
*/
public function unverified()
{
return $this->state(fn (array $attributes) => [
'email_verified_at' => null,
]);
}
}
Here are all of the Migrations:
2014_10_12_000000_create_users_table.php:
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('users');
}
};
2022_12_08_154030_create_projekts_table.php:
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('projekts', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger('user_id');
$table->string('name');
$table->timestamps();
$table->softDeletes();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('projekts');
}
};
2022_12_08_154042_create_posts_table.php:
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('posts', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger('user_id');
$table->string('title');
$table->text('body');
$table->timestamps();
$table->softDeletes();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('posts');
}
};
2022_12_09_114733_create_projekt_user_pivots_table.php:
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('projekt_user_pivots', function (Blueprint $table) {
$table->unsignedBigInteger('user_id');
$table->unsignedBigInteger('projekt_id');
$table->primary(['user_id','projekt_id']);
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('projekt_user_pivots');
}
};
Here are all Seeders:
DatabaseSeeder.php:
<?php
namespace Database\Seeders;
// use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use App\Models\Post;
use App\Models\User;
use App\Models\Projekt;
use App\Models\ProjektUserPivot;
use Illuminate\Database\Seeder;
class DatabaseSeeder extends Seeder
{
/**
* Seed the application's database.
*
* #return void
*/
public function run()
{
User::factory(10)
->has(Post::factory()->count(10))
->has(Projekt::factory()->count(2))
->has(ProjektUserPivot::factory()->count(4))
->create();
}
}
PostSeeder.php:
<?php
namespace Database\Seeders;
use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;
class PostSeeder extends Seeder
{
/**
* Run the database seeds.
*
* #return void
*/
public function run()
{
//
}
}
ProjektSeeder.php:
<?php
namespace Database\Seeders;
use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;
class ProjektSeeder extends Seeder
{
/**
* Run the database seeds.
*
* #return void
*/
public function run()
{
}
}
ProjektUserPivotSeeder.php:
<?php
namespace Database\Seeders;
use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;
class ProjektUserPivotSeeder extends Seeder
{
/**
* Run the database seeds.
*
* #return void
*/
public function run()
{
//
}
}
I know why the problem arises but how can I solve it?
Working migration and seeding
Not working migration and seeding
Laravel and its ORM Eloquent work better if you use exactly what they ask for: the pivot tabel between two table must be constructed as the following:
Schema::create('first_second', function(Blueprint $table)
{
$table->increments('id');
$table->integer('first_id');
$table->integer('second_id');
});
In your example, your pivot table is named projekt_user_pivot, and the ORM can't access it natively. Plus, Eloquent adds the automatic plural to the table, to it tries to find a table named projekt_user_pivots.
Add the $table->increments('id'); in the migration of your ProjektUser migration, and I suggest to follow Laravel's guidelines. You won't even need to create the model ProjektUser as Eloquent will do it itself.
~~
How to create your pivot table:
Make a migration (php artisan make:migration create_projekt_user_table)
function up() {
Schema::create('projekt_user', function(Blueprint $table)
{
$table->increments('id');
$table->integer('projekt_id');
$table->integer('user_id');
});
}
In your Models :
User.php
public function projekts()
{
$this->belongsToMany(User::class);
}
Projekt.php
public function users()
{
$this->belongsToMany(Projekt::class);
}
And your factories :
UserFactory.php
$projekts = Projekt::factory()->count(3)->create();
$user = User::factory()
->count(3)
->hasAttached($projekts)
->create();
This code will create 3 Users and 3 Projects, and all the Users will be linked to the 3 projekts in the pivot table, creating 9 lines.
With the definitions in the models that there is a many to many relationship between User and Projekt, your factory won't have any problem to populate itself the pivot table.
Note: if you ever need to add some additional data inside your pivot table (for example a role for the user for this specific project), you just have to update the migration to add the field, and you can define it with :
User.php
public function projekts()
{
$this->belongsToMany(User::class)->withPivot('role');
}
And you'll be able to access it in you code with :
foreach($user->projekts as $projekt)
{
echo $projekt->pivot->role;
}
I would appreciate in advance the help you could give me about the next problem that I can't solve.
I have 3 Tables
Contracts
Currencies
Amounts
and a Pivot Table
contract_currency_amount
Here I show you the migrations
Contracts
<?php
use Carbon\Carbon;
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateContractsTable extends Migration
{
/**
* Contracts Table
*
* #var string
*/
private $table = 'contracts';
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create($this->table, function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('number')->unique();
$table->string('name');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists($this->table);
}
}
Currencies
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateCurrenciesTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('currencies', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('abbreviation');
$table->string('description');
$table->boolean('active')->default(true);
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('currencies');
}
}
Amounts
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateAmountsTable extends Migration
{
/**
* Amounts Table
*
* #var string
*/
private $table = 'amounts';
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create($this->table, function (Blueprint $table) {
$table->bigIncrements('id');
$table->float('amount');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists($this->table);
}
}
Contract_Currency_Amount Pivot Table
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateContractCurrencyAmountTable extends Migration
{
/**
* Pivot Table
*
* #var string
*/
private $table = 'contract_currency_amount';
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create($this->table, function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedInteger('contract_id');
$table->unsignedInteger('currency_id');
$table->unsignedInteger('amount_id');
$table->timestamps();
$table->foreign('contract_id')
->references('id')->on('contracts')
->onDelete('cascade');
$table->foreign('currency_id')
->references('id')->on('currencies')
->onDelete('cascade');
$table->foreign('amount_id')
->references('id')->on('amounts')
->onDelete('cascade');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists($this->table);
}
}
I have created the models for each of those tables, including a model for the pivot table, but I don't know how to make a query to the pivot table so that it returns all the data of a specific record, relating the 3 tables. for example I want in a view with Blade to go through a variable to show all the amounts, of a specific contract, and to be able to go through that variable in the following way:
#foreach($amounts as $amount)
{{ $amount->currency->abbreviation }}
#endforeach
I mean, I want the query to return the related values of the 3 tables. I have no experience in the use of pivot tables, I would appreciate any help ..
EDIT 1
Amount Model
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Amount extends Model
{
/**
* Attributes that should be mass-assignable.
*
* #var array
*/
protected $fillable = ['amount'];
}
Currency Model
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
/**
* Class Currency
*
* #property $id
* #property $abbreviation
* #property $description
* #property $active
* #property $created_at
* #property $updated_at
*
* #package App
* #mixin \Illuminate\Database\Eloquent\Builder
*/
class Currency extends Model
{
/**
* Attributes that should be mass-assignable.
*
* #var array
*/
protected $fillable = ['abbreviation','description','active'];
}
Contract model
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use App\Models\Entity;
use App\Models\CInitiative;
class Contract extends Model
{
// TODO: This!
}
ContractCurrencyAmount Model
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Relations\Pivot;
class ContractCurrencyAmount extends Pivot
{
protected $table = 'contract_currency_amount';
}
In order to achieve what you are looking for you must setup your models correctly. You must setup you ContractCurrencyAmount Model to be a normal eloquent model instead of extending pivot.
ContractCurrencyAmount
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class ContractCurrencyAmount extends Model
{
protected $table = 'contract_currency_amount';
public function contract()
{
return $this->belongsTo('App\Contract');
}
public function currency()
{
return $this->belongsTo('App\Currency');
}
public function amount()
{
return $this->belongsTo('App\Amount');
}
}
Contract
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Contract extends Model
{
public function relations()
{
return $this->hasMany('App\ContractCurrencyAmount', 'contract_id');
}
}
Currency
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Currency extends Model
{
public function relations()
{
return $this->hasMany('App\ContractCurrencyAmount', 'currency_id');
}
}
Amount
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Currency extends Model
{
public function relations()
{
return $this->hasMany('App\ContractCurrencyAmount', 'amount_id');
}
}
Then you can do this:
foreach($amounts as $amount) {
{
foreach($amount->relations as $relation) {
$relation->currency->abbreviation;
}
}
You can also make use of eager loading to optimize your database queries:
$amounts = Amount::with('relations.currency')->get();
This will preload all the data you need in the for loops above, instead of querying the database on each iteration.
I have my users and photos tables create. Now that I added the photo_id into my users table, I am unable to register a user and it gives me an error saying that photo_id does not have a default value.
Here my User Model:
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'password','photo_id'
];
public function photo(){
return $this->belongsTo('App\Photo');
}
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
}
Photo Model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Photo extends Model
{
//
protected $fillable = ['path'];
}
Users Migration table
class CreateUsersTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->integer('photo_id');
$table->string('name');
$table->string('email')->unique();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('users');
}
}
And here My photo migration
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreatePhotosTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('photos', function (Blueprint $table) {
$table->increments('id');
$table->string('path');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('photos');
}
}
This is what I see when I try to register a user:
I have a case where 2 eloquent models should inherit properties from a User model, but the User itself should not exist as a standalone instance. (Mentors and Students, both inherit from User class). So what I'm currently doing is:
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
abstract class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
/**
* Get the courses that the user has enrolled into
*
* #return \Illuminate\Database\Eloquent\Relations\HasMany
*/
public function courses()
{
return $this->hasMany('App\Models\Course', 'user_course', 'user_id', 'course_id');
}
}
class Student extends User
{
protected $table = 'students';
/**
* Get the mentors that the user has hired
*
* #return \Illuminate\Database\Eloquent\Relations\HasMany
*/
public function mentors()
{
return $this->hasMany('App\Models\User');
}
}
class Mentor extends User
{
protected $table = 'mentors';
/**
* Get a list of courses that a mentor is teaching
*
* #return \Illuminate\Database\Eloquent\Relations\HasMany
*/
public function ownCourses()
{
return $this->hasMany('App\Models\Course', 'mentor_course', 'mentor_id', 'course_id');
}
}
I am wondering whether this is the correct to do what I am trying to accomplish?
IMHO I will use polymorhic relation:
Use three tables: users, students and mentors; in the users table add two fields: userable_id (integer), userable_type (string).
User model
class class User extends Authenticatable
{
public function userable()
{
return $this->morphTo();
}
Student model:
class Student extends Model
{
public function user()
{
return $this->morphOne('App\User', 'userable');
}
Mentor model:
class Mentor extends Model
{
public function user()
{
return $this->morphOne('App\User', 'userable');
}
Now User::find($id)->userable return a Student or a Mentor object depending on the value of the userable_type
I leave the others relations to you, I hope this helps.
i have these two models:
<?php namespace App\Models;
use Illuminate\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Auth\Passwords\CanResetPassword;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;
class User extends Model {
use Authenticatable, CanResetPassword;
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'users';
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = ['name', 'email', 'password', 'is_active'];
/**
* The attributes excluded from the model's JSON form.
*
* #var array
*/
protected $hidden = ['password', 'remember_token'];
public function customer_details()
{
return $this->hasOne('CustomerDetails', 'user_id');
}
}
And:
<?php namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class CustomerDetails extends Model {
protected $table = 'customer_details';
public function user()
{
return $this->belongsTo('User');
}
}
Now i am trying to get all customers along with their user data from the database in my index() of my UserController():
/**
* Display a listing of the resource.
*
* #return Response
*/
public function index()
{
$users = User::with('customer_details')->get();
return [
'users' => $users
];
}
But i keep getting this error:
Fatal Error Exception Class 'CustomerDetails' not found
I have no idea what i am doing wrong here.
Your class is namespaced and should therefore be referred to as App\Models\CustomerDetails, in the $this->hasOne(...) definition of customer_details of the App\Models\User model.