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.
Related
I'm working on a Laravel 8 project.
I have a payments table, it's the migration:
Schema::create('payments', function (Blueprint $table) {
$table->id();
$table->enum('gateway',['idpay','zarinpal']);
$table->unsignedInteger('res_id')->nullable();
$table->char('ref_code',128)->nullable();
$table->enum('status',['paid','unpaid']);
$table->unsignedBigInteger('order_id');
$table->foreign('order_id')->references('id')->on('orders')->onDelete('cascade');
$table->timestamps();
});
as you can see this table has a foreign key that references on orders table, and it is orders migration:
Schema::create('orders', function (Blueprint $table) {
$table->id();
$table->unsignedInteger('amount');
$table->char('ref_code',128)->nullable();
$table->enum('status',['unpaid','paid',]);
$table->unsignedBigInteger('user_id');
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->timestamps();
});
I created a one to one relationship in Order model:
class Order extends Model
{
use HasFactory;
protected $guarded = [];
public function payment()
{
return $this->hasOne(Payment::class);
}
}
The problem is that when I want to use order() method on Payment class it does not work.
for example:
Payment::find(10)->order()->update(['status' =>'paid']);
I get this error:
BadMethodCallException Call to undefined method
App\Models\Payment::order()
UPDATE:
Here is Payment model:
class Payment extends Model
{
use HasFactory;
protected $guarded = [];
}
Thank you for helping me.
You should use like this a method in the payment model.
public function order()
{
return $this->belongsTo(Order::class);
}
Because you still don't have any relationship in the payment model to order.
You can check here for detailed information.
https://laravel.com/docs/8.x/eloquent-relationships#one-to-one-defining-the-inverse-of-the-relationship
You have to describe the order relation ship in the Payment model
class Payment extends Model
{
use HasFactory;
protected $guarded = [];
public function order()
{
return $this->belongsTo(Order::class);
}
}
and after that you can access the payment's order like this:
Payment::find(10)->order->update(['status' =>'paid']);
I get an error when calling $ event-> courts
"message": "SQLSTATE[42S22]: Column not found: 1054 Unknown column 'courts.events_id' in 'where clause' (SQL: select * from courts where courts.events_id = 1 and courts.events_id is not null)",
Events
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Events extends Model
{
use HasFactory;
/**
* #var string[]
*/
protected $fillable = [
'user_id',
'event_name',
'frequency',
'start_date',
'end_date',
'day',
'session_time',
];
public function scopeMy($query)
{
return $query->where('user_id', auth()->id());
}
public function courts()
{
return $this->hasMany(Court::class);
}
}
Court
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Court extends Model
{
use HasFactory;
/**
* #var string[]
*/
protected $fillable = [
'event_id',
'name',
];
public function event(){
return $this->belongsTo(Events::class);
}
}
Migration
Events
public function up()
{
Schema::create('events', function (Blueprint $table) {
$table->id();
$table->foreignId('user_id')->constrained()->cascadeOnDelete();
$table->string('event_name')->nullable();
$table->string('frequency')->nullable();
$table->string('start_date')->nullable();
$table->string('end_date')->nullable();
$table->string('day')->nullable();
$table->string('session_time')->nullable();
$table->timestamps();
});
}
Courts
public function up()
{
Schema::create('courts', function (Blueprint $table) {
$table->id();
$table->foreignId('event_id')->constrained()->cascadeOnDelete();
$table->string('name')->nullable();
$table->timestamps();
});
}
you have to mention your foreign key in the Events model relationship for the Court Model.
Eloquent will automatically determine the proper foreign key column for the Child model. By convention, Eloquent will take the "snake case" name of the parent model and suffix it with _id.
your model name is Events and the foreign key is event_id in Court Model, singular and plural issue.
so change the relationship in Events model adding the second parameter
public function courts()
{
return $this->hasMany(Court::class, 'event_id');
}
You need to change relation. You have to pass manually foreignKey and ownerKey
public function event(){
return $this->belongsTo(Events::class,'event_id','id');
}
Then in court model also you need to change
public function courts()
{
return $this->hasMany(Court::class, 'event_id','id');
}
How to get a list of Category and subcategories like this:
1 mobile
apple
samsung
nokia
2:Laptops
Mac
HP
Dell
Sony
3:Tvs
Samsung
using query builder in controller and foreach loop in view
My Controller
$sub_catagories = DB::table('books_categories')
->join('sub_catagories','sub_catagories.catId','=','books_categories.catId')->get();
return view('index',compact('sub_catagories'));
My category table
public function up()
{
Schema::create('books_categories', function (Blueprint $table) {
$table->increments('catId');
$table->string('catName', 50)->nullable(false);
$table->timestamps();
});
}
My sub_catagory table
public function up()
{
Schema::create('sub_catagories', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->integer('catId');
$table->timestamps();
});
}
I've written some example of whole cycle. There is convention in laravel to use unique auto increment 'id's, and have foreign keys like RELATION_id. So if you want to change the table and column names anyway, you can do that with following to this example:
Category Model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Category extends Model
{
protected $table = 'categories';
protected $fillable = [
'id',
'name',
];
public function subcategories(){
return $this->hasMany(Subcategory::class, 'category_id', 'id');
}
}
Subcategory Model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Subcategory extends Model
{
protected $table = 'subcategories';
protected $fillable = [
'id',
'category_id',
'name',
];
public function category(){
return $this->belongsTo(Category::class, 'category_id');
}
}
categories table Migration
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateCategoriesTable extends Migration
{
public function up()
{
Schema::create('categories', function (Blueprint $table) {
// PRIMARY
$table->bigIncrements('id');
// ADDITIONAL
$table->string('name');
// TIME
$table->timestamps();
});
}
public function down()
{
Schema::dropIfExists('categories');
}
}
subcategories table Migration
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateSubcategoriesTable extends Migration
{
public function up()
{
Schema::create('subcategories', function (Blueprint $table) {
// PRIMARY
$table->bigIncrements('id');
// FOREIGN
$table->unsignedBigInteger('category_id')->nullable();
$table->foreign('category_id')->references('id')->on('categories')->onDelete('cascade')->onUpdate('cascade');
// ADDITIONAL
$table->string('name');
// TIME
$table->timestamps();
});
}
public function down()
{
Schema::dropIfExists('subcategories');
}
}
usage in controller
// 1
public function categories()
{
$categories = Category::all()->get();
return view('categories', [
'categories' => $categories,
]);
}
// 2
public function catsWithSubcats()
{
$cats_with_subcats = Category::with('subcategories')->get();
return view('cats_with_subcats', [
'categories' => $cats_with_subcats,
]);
}
// 3
public function subcatsWithCats()
{
$subcats_with_cats = Subcategory::with('category')->get();
return view('subcats_with_cats', [
'subcategories' => $subcats_with_cats,
]);
}
If you want to show all categories with their subcategories in the blade, you don't need to use 2nd or 3rd method, just use 1st method. Create "categories.blade.php" inside of "resources/views/..." and write there something like this:
#foreach($categories as $category)
#foreach($category->subcategories as $subcategory)
<p>{{ $subcategory->name }}</p>
#endforeach
#endforeach
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 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