How do I create A joined table in Laravel Migration? - laravel

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);

Related

Get attribute in model - laravel eloquent

In laravel i can getFirstNameAttribute in my products model and change the value but I'm create this column "priceArray" and i can not get attributes because The first letter in the second word is capital letters and model can not found this column.
public function getPriceArrayAttribute($value)
{
return 'test';
}
Its not work and can not get "priceArray" column
This is my migration
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateProductsTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('products', function (Blueprint $table) {
$table->id();
$table->string('title')->nullable();
$table->string('price')->nullable();
$table->string('priceArray')->nullable();
$table->text('items')->nullable();
$table->enum('status',['active','inactive','unavailable'])->default('inactive');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('products');
}
}
This is my product model
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
/**
* Class Products
* #package App\Models
* #property Variants Variants
*/
class Products extends Model
{
use HasFactory;
protected $guarded=[];
protected $changePrice=0;
public function Insert($data)
{
return self::create($data);
}
public function getPriceArrayAttribute($value)
{
return 'test';
}
public function getPriceAttribute($value)
{
return ceil($value);
}
}
The getPriceAttribute is worked but getPriceArrayAttribute does not worked
I think you are trying to modify the priceArray value after it is retrieved from the database, the way you did with ceil() on the price attribute. The only way this works is if you change the column name to price_array. This is by far the simplest fix.
Migration
Schema::create('products', function (Blueprint $table) {
$table->id();
$table->string('title')->nullable();
$table->string('price')->nullable();
$table->string('price_array')->nullable();
$table->text('items')->nullable();
$table->enum('status',['active','inactive','unavailable'])->default('inactive');
$table->timestamps();
});
Model
public function getPriceArrayAttribute($value)
{
return 'test';
}
You must follow Eloquent's rules: you use snake case for the attributes. The getPriceArrayAttribute accessor will automatically be called by Eloquent when you retrieve the value of the price_array attribute.
$table->string('price_array')->nullable();

How can I use Softdeletes in the models of Employee and User?

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.

How can i store data in table from controller store method? i have two table in one migration file

I have created a model with migration file by artisan co
mmand
php artisan make:model Staff -m
Created two table in migration file
Schema::create('staffcat', function (Blueprint $table) {
});
Schema::create('staff', function (Blueprint $table) {
});
Now trying to store data to staffcat table from StaffController by
store method. But it's not finding staffcat table :(
I created another model Staffcat. But no luck :(
Create_staff_table File
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateStaffTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('staffcat', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('catname');
});
Schema::create('staff', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('user_id');
$table->string('name');
$table->string('designaton');
$table->string('nid')->nullable();
$table->date('dob');
$table->date('doj');
$table->string('blood')->nullable();
$table->string('mpoin')->nullable();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('staffcat');
Schema::dropIfExists('staff');
}
}
Staff Model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Staff extends Model
{
//
}
store method in StaffController
public function store(Request $request)
{
//
$this->validate($request,[
'st_cat_name' => 'required'
]);
$staffinfo = new Staff;
$staffinfo->catname = $request->input('st_cat_name');
$staffinfo->save();
return redirect('/staff')->with('success', 'Staff category Created');
}
Here is the error message
"SQLSTATE[42S02]: Base table or view not found: 1146 Table 'gchsc.staffcats' doesn't exist (SQL: insert into staffcats
(catname, updated_at, created_at)
I want to store data in staffcat table

laravel hasone not able to get the result

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;

Laravel 5.1 how to attach the Order to a User using Pivot Tables?

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');
}

Resources