i'm trying to get the role of a user either is it admin or client with hasOne relationship but when i'm trying to get the details and doing dd im getting the exists as false can anyone help me out please
this is the result when im using dd in controller
//migration for user
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('email')->unique();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}
//migration for role
public function up()
{
Schema::create('roles', function (Blueprint $table) {
$table->increments('id');
$table->unsignedInteger('user_id');
$table->enum('role',['Club Manager','Admin','Mc']);
$table->foreign('user_id')->references('id')->on('users');
$table->timestamps();
});
}
//UserModel
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
use \App\Role;
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',
];
public function Role(){
return null;
}
public function getrole(){
$role=$this->hasMany('App\Role');
return $role;
}
public function getuserRole(){
return Role::where('user_id',$this->id)->first();
}
}
//Controller
public function getrole(){
dd(Auth::user()->getrole());
}
You have to access the relationship as a property, not as a method:
Auth::user()->getrole;
Related
I have this model :
class User extends Authenticatable
{
protected $fillable = [
'email',
'password',
'role_id',
];
.........
public function language() {
return $this->hasOne(Language::class, 'language_id');
}
}
And Language model :
class Language extends Model
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name',
'iso'
];
/**
* #return BelongsTo
*/
public function user()
{
return $this->belongsTo(User::class);
}
Now When I try to save user :
$newUser->language()->save(Language::find($input['language']));
I get the error:
Column not found: 1054 Unknown column 'language_id' in 'field list' (SQL: update `languages` set `language_id` = 4, `languages`.`updated_at` = 2021-08-02 13:51:32 where `id` = 1)"
User migration :
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->integer('role_id')->default(UserRoles::TRANSLATOR);
$table->integer('language_id')->references('id')->on('languages')->nullable();
$table->rememberToken();
$table->timestamps();
$table->softDeletes();
});
}
Language migration :
public function up()
{
Schema::create('languages', function (Blueprint $table) {
$table->id();
$table->timestamps();
$table->string('name');
$table->string('iso')->unique();
});
}
I confirm that I have language id inside users table and I don't have user_id inside language table, because I want to keep just language_id inside table. What can I try next?
When you have hasOne in User model:
public function language() {
return $this->hasOne(Language::class, 'language_id');
}
eloquent assumes that languages table would have language_id. Hence the error 'no language_id in languages table'
So, hasOne should be defined in the the Language model.
//Language model
public function user() {
return $this->hasOne(User::class); //this assumes users table would have language_id
}
And, the belongsTo should be defined in User model.
//User model
public function language() {
return $this->belongsTo(Language::class);
}
as the first answer, change the sintax of your relationship and add the language_id to the fillable array
user model
protected $fillable = [
'email',
'password',
'role_id',
'language_id'
];
public function language() {
return $this->belongsTo(Language::class);
}
and on user creation
$user = User::create(
'email' => ...
'password' => ...
'role_id' => ...
'language_id' => $input['language']
);
you can see more here https://laravel.com/docs/8.x/eloquent-relationships#the-save-method, so in this case if you want to use the save method on this relation you must do it like
$language = Language::find($input['language']);
$language->user()->save($newuser);
I suggest use the Laravel documentation sintax for the relationship in migration
$table->foreignId('language_id')->constrained()->nullable();
Employee Migration
public function up()
{
Schema::create('employees', function (Blueprint $table) {
$table->increments('id');
$table->string('name', 60);
$table->string('phone_whats', 30)->nullable();
$table->string('phone_home', 30)->nullable();
$table->string('email', 255)->nullable();
$table->string('dt_birthday', 20)->nullable();
$table->string('zipcode', 20)->nullable();
$table->integer('id_city')->unsigned();
$table->integer('id_state')->unsigned();
$table->string('address', 255)->comment('Endereço')->nullable();
$table->string('number', 10)->nullable();
$table->string('rg', 25)->nullable();
$table->string('cpf', 20)->nullable();
$table->string('password', 255)->nullable();
$table->foreign('id_city')->references('id')->on('cities');
$table->foreign('id_state')->references('id')->on('states');
$table->timestamps();
$table->softDeletes();
});
}
public function down()
{
Schema::dropIfExists('employees');
}
User Migration
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->Increments('id');
$table->string('name',255);
$table->integer('id_employee')->unsigned();
$table->string('email',255)->unique();
$table->string('password',255);
$table->foreign('id_employee')->references('id')->on('employees');
$table->timestamps();
$table->softDeletes();
});
}
public function down()
{
Schema::dropIfExists('users');
}
My Model Employee
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Facades\Auth;
class Employee extends Model
{
use SoftDeletes;
protected $hidden = ['created_at', 'deleted_at', 'updated_at'];
protected $dates = ['deleted_at'];
protected $fillable = [
'name', 'phone_home', 'phone_whats','email', 'dt_birthday', 'number', 'rg', 'cpf', 'address',
'id_state', 'id_city', 'password'
];
}
My Model User
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class User extends Model
{
use SoftDeletes;
}
Employee Controller
public function destroy(Employee $employee)
{
$employee->delete();
return redirect()->back();
}
I would like to use softdeletes in the registration of employees and users, when I tested only in the Employee Controller register, my database registration was deleted, I just wanted to apply softdeletes in the employee and the user in the same function, keeping the registration in the database and just fill in the delete_at columns of the two databases leaving them inactive.
Looking at the code, it should work - have you runned migrations (if you have added softDeletes later)? How do you know your record was deleted? Have you checked it directly in database, or via Eloquent? As SoftDeletes trait implictly adds to every query clause, returning only models which are not deleted softly, so via User::find() you wouldn't get model that was deleted softly.
I have a users table with the following columns with User model has one to many relationship with phone model.
create_users_table.php
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}
Then I have a phones table, which has a foreign key of user_id
create_phones_table.php
public function up()
{
Schema::create('phones', function (Blueprint $table) {
$table->bigIncrements('id');
$table->integer('user_id')->unsigned();
$table->string('phone');
$table->timestamps();
$table->foreign('user_id')
->references('id')
->on('users')
->onDelete('cascade');
});
}
My User Model
<?php
namespace App;
use App\Phone;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
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',
];
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
/**
* Define Relationship
*/
public function phones()
{
return $this->hasMany(Phone::class);
}
}
My Phone Model
<?php
namespace App;
use App\User;
use Illuminate\Database\Eloquent\Model;
class Phone extends Model
{
protected $table = 'phones';
protected $fillable = ['phone' , 'user_id'];
public function user()
{
return $this->belongsTo(User::class);
}
}
I would like to have a third table in my database call phone_user_table.php. Something like a pivot table where I have joined the user table and phone table where I can see all the records. This is my code where I attempt to join the table.
create_phone_user.php
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreatePhoneUser extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('phone_user', function (Blueprint $table) {
$table->unsignedBigInteger('user_id')->unsigned();
$table->unsignedBigInteger('phone_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->foreign('phone_id')->references('id')->on('phones')->onDelete('cascade');
$table->timestamps();
$table
->join('users', 'users.id', '=', 'phone_user.user_id')
->join('phones', 'phones.id', '=', 'phone_user.phone_id')
->select('phone_user.*', 'users.name', 'phones.phone')
->get();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('phone_user');
}
}
However, it seems to be giving Base Table phones already exist.
Appreciate all the help given.
Thank you.
This is how it works base on Laravel Many to Many Relationship Docs.
First
You need to create 2 model that you would like to have relationship.
In your example you have USER and PHONE relationship.
In your User Model you need to declare the relationship like this:
public function phones() {
return $this->belongsToMany(Phone::Class);
}
And In your Phone Model you can do like this:
public function users() {
return $this->belongsToMany(User::Class);
}
SECOND
You need to have 3 migration one is for the user, phone and also the phone_user. So it should be look like this.
Phone User Migration
Schema::create('phone_user', function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedBigInteger('phone_id')->index();
$table->unsignedBigInteger('user_id')->index();
$table->timestamps();
$table->foreign('phone_id')->references('id')->on('phones')->onDelete('cascade');
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
});
Note: You don't need to have the unsignedBigInteger in both user and phone migration.
When you have a user list and a phone list you can now assign the phone to the user like this:
Controller
$user = User::find(1);
$phone = Phone::find(1);
$user->phones()->attach($phone);
I'm trying to define a role for my users using a "role_id" foreign key which referes to the "id" of my "roles" table.
The migrations worked well but when I'm trying to register I get an error.
Migration users
class CreateUsersTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->bigIncrements('id');
$table->char('nni', 6);
$table->string('firstname');
$table->string('lastname');
$table->string('email')->unique();
$table->unsignedBigInteger('role_id')->default(1);
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
$table->foreign('role_id')->references('id')->on('roles');
});
}
Models/User
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'nni', 'firstname', 'lastname', 'email', 'role_id', 'admin', 'password',
];
[...]
public function role()
{
return $this->belongsTo(Role::class);
}
}
Migration roles
class CreateRolesTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('roles', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->string('description');
$table->timestamps();
});
}
[...]
}
The error
SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update >a child row: a foreign key constraint fails (projectsms.users, >CONSTRAINT users_role_id_foreign FOREIGN KEY (role_id) REFERENCES >roles (id))
If you know where is my problem let me know !
Since your structure depends on the fact that every use must have a role, you should include the insertion of the default role in your migration.
class CreateRolesTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('roles', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->string('description');
$table->timestamps();
});
DB::table('roles')->insert([
'id' => 1, //must be 1
'name' => 'default',
'description' => 'default role (just registered)',
'created_at' => \Carbon\Carbon::now(),
'updated_at' => \Carbon\Carbon::now(),
]);
}
[...]
}
So i am trying to build a structure where One User can have Many Orders and One order has 2 Users(eg: the customer and the employee servicing that order).
This is my migrations:
Orders to Users:
Schema::create('order_user', function (Blueprint $table) {
$table->increments('id')->unsigned();
$table->integer('user_id')->unsigned()->index();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->integer('order_id')->unsigned()->index();
$table->foreign('order_id')->references('id')->on('orders')->onDelete('cascade');
$table->timestamps();
});
Order:
Schema::create('orders', function (Blueprint $table) {
$table->increments('id');
$table->string('boostFrom')->nullable();
$table->string('boostTo')->nullable();
$table->string('numGames')->nullable();
$table->decimal('totalPrice');
$table->string('ipnStatus');
$table->timestamps();
});
Users:
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('email')->unique();
$table->string('password', 60);
$table->rememberToken();
$table->timestamps();
});
I have not set relationships yet since i test with them already in my User and Order Models. But when i try to attach the Order to User using:
$user->order()->attach(4);
I get an error relating to Builder.php saying attach() does not exist, but i was following the laravel 5.1 docs to try to attach the order.
Could you please let me know how i should structure everything so when an order is created then i can attach that to a user.
Thanks
As Requested:
class Order extends Model
{
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'orders';
public function users()
{
return $this->hasMany('App\Models\User');
}
}
class User extends Model implements AuthenticatableContract, CanResetPasswordContract, HasRoleAndPermissionContract
{
use Authenticatable, CanResetPassword, HasRoleAndPermission;
/**
* 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'];
/**
* The attributes excluded from the model's JSON form.
*
* #var array
*/
protected $hidden = ['password', 'remember_token'];
protected $guarded = ['id'];
public function orders()
{
return $this->hasMany('App\Models\Order');
}
}
Error in Tinker:
>>> $user->orders()->attach(4)
BadMethodCallException with message 'Call to undefined method Illuminate\Database\Query\Builder::attach()'
You should be using belongsToMany, instead of hasMany, since you have a many-to-many relationship. The hasMany is used to define a one-to-many relation. So you should have this:
// Order.php
public function users()
{
return $this->belongsToMany('App\Models\User');
}
and this
// User.php
public function orders()
{
return $this->belongsToMany('App\Models\Order');
}