I just wanted to clarify using the relationship in tables. Right now, I wanted to fetch records of designation names from designation_id in employees table.
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use App\Models\{
Designations,
Positions
};
class Employees extends Model
{
use HasFactory;
protected $table = 'employees';
protected $primaryKey = 'id';
public $timestamps = true;
protected $casts = [
'designation_id' => 'array',
'position_id' => 'array',
'basic_pay' => 'decimal:2',
];
protected $dates = ['created_at', 'updated_at'];
protected $fillable = [
'first_name',
'last_name',
'designation_id',
'position_id',
'basic_pay',
];
public function designations()
{
return $this->hasMany(Designations::class, 'id', 'designation_id');
}
public function positions()
{
return $this->hasMany(Positions::class, 'id', 'position_id');
}
}
Here's my designation model:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use App\Models\Employees;
class Designations extends Model
{
use HasFactory;
protected $table = 'designations';
protected $primaryKey = 'id';
public $timestamps = true;
protected $dates = ['created_at', 'updated_at'];
protected $fillable = [
'name',
'description'
];
public function employees()
{
return $this->belongsTo(Employees::class, 'designation_id');
}
}
Here's my EmployeeController.php:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\{
Employees,
Designations
};
class EmployeesController extends Controller
{
public function index()
{
$employees = Employees::with('designations', 'positions')->get();
return array_reverse($employees);
}
}
I checked my api url, http://localhost:8000/api/employees and got this error:
SQLSTATE[HY093]: Invalid parameter number (SQL: select * from designationswheredesignations.id in (52))
I would recommend you to install phpstorm, it gives you hints of function parameters and you won't have this kind of issues anymore.
correct format is:
return $this->hasMany('App\Comment', 'foreign_key', 'local_key');
in your designations model:
public function DesignationNames()
{
return $this->hasMany(\App\Models\Employees::class, 'designation_id', 'id');
}
When you retrieve them in your controller you need to use the with() method as:
Designations::with('DesignationNames')->get();
And then to access properties in the related employee collection you would need to:
$designation->DesignationNames->DesignationProperty
Your relationships parameters are wrong. It's
hasMany(class, foreignKey, relatedPrimaryKey)
# Employee
public function designations()
{
return $this->hasMany(Designations::class, 'employee_id', 'id');
}
public function positions()
{
return $this->hasMany(Positions::class, 'employee_id', 'id');
}
If you're eager loading more than 1 relationship, use array notation.
Also, $employees will be an instance of a Collection, so you can't use it as an argument to array_reverse.
You can either use collection methods to achieve the same result, or use $employees->all() to get the underlying array.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Employees;
class EmployeesController extends Controller
{
public function index()
{
$employees = Employees::with(['designations', 'positions'])->get();
return $employees->reverse()->values()->all();
// OR
return array_reverse($employees->all());
}
}
This is assuming your tables have a structure like this:
Schema::create('employees', function (Blueprint $table) {
$table->id();
...
});
Schema::create('designations', function (Blueprint $table) {
$table->id();
$table->foreignId('employee_id')->constained('employees');
...
});
Schema::create('positions', function (Blueprint $table){
$table->id();
$table->foreignId('employee_id')->constained('employees');
...
});
Since you're using increments instead of id(), the code has to be a little different.
Schema::create('employees', function (Blueprint $table) {
$table->increments('id')->unique();
...
});
Schema::create('designations', function (Blueprint $table) {
$table->increments('id')->unique();
$table->unsignedInteger('employee_id');
$table->foreign('employee_id')->references('id')->on('employees');
...
});
Schema::create('positions', function (Blueprint $table){
$table->increments('id')->unique();
$table->unsignedInteger('employee_id');
$table->foreign('employee_id')->references('id')->on('employees');
...
});
Related
I have a many:many relation between student and course.
Here are my models and my pivot table:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Student extends Model
{
use HasFactory;
protected $fillable = [
'name',
'surname',
'age',
'tdah',
'description',
'hobbies',
];
/* public function course(){
return $this->belongsTo(Course::class);
} */
public function data(){
return $this->hasMany(Datum::class, 'student_id', 'id');
}
public function configurations(){
return $this->hasMany(Configuration::class, 'student_id', 'id');
}
public function courses(){
return $this->belongsToMany(Course::class, 'course_student', 'student_id', 'course_id');
}
}
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Course extends Model
{
use HasFactory;
protected $fillable = [
'name',
'academic_course_id',
'user_id',
];
public function user()
{
return $this->belongsTo(User::class);
}
public function academicCourse()
{
return $this->belongsTo(AcademicCourse::class);
}
public function planification(){
return $this->hasOne(Planification::class, 'course_id', 'id');
}
public function subjects(){
return $this->hasMany(Subject::class, 'course_id', 'id');
}
/* public function students(){
return $this->hasMany(Student::class, 'course_id', 'id');
} */
public function students(){
return $this->belongsToMany(Student::class, 'course_student', 'course_id', 'student_id');
}
}
<?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('course_student', function (Blueprint $table) {
$table->id();
$table->foreignId('course_id')->constrained()->onDelete('cascade');
$table->foreignId('student_id')->constrained()->onDelete('cascade');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('course_student');
}
};
I'd like to create a student that belongs to a group. I know how to create a student and a group, but I'd like to create a register for that student in my course_student pivot table. My StudentController method store is:
public function store(Request $request)
{
Student::create($request->all());
$courses = Course::all();
$academicCourses = AcademicCourse::all();
return view('course.index', compact('courses', 'academicCourses'));
}
It creates a new student but I don`t know how to create a new register for the pivot table.
I thought about doing something like:
course_student::create(request)
in my store method but I think it isn`t that way.
In Laravel you can do it by using attach function, Attach() function has two parameters :
1- the another foreign key in you case attach(course_id).
2-(this is optional) array for any another columns inside pivot table for example :
attach(course_id,['users_id'=>$usersId])
In your case you will create the records inside the pivot table (course_student) via the object from student model .
$student->courses()->attach($course_id);
note :
there is another method which does the opposite detach() but you need to use it carefully if you write it without any parameter it will remove all the records inside (course_student) that belong to the student object so specify the course that you want to remove it by that way :
$student->courses()->detach($course_id);
I hope that will help you ...
$student->courses()->attach($courseId);
https://laravel.com/docs/9.x/eloquent-relationships#updating-many-to-many-relationships
Edit :
You can use attach() method on the relationship. In your code it would look like this :
public function store(Request $request, Course $course) //add parameter course to know which course needs to be attached
{
$newStudent = Student::create($request->all()); // create() returns instance of created Student
$newStudent->courses()->attach($course->id);
$courses = Course::all();
$academicCourses = AcademicCourse::all();
return view('course.index', compact('courses', 'academicCourses'));
}
I have a users table, a message table and a user-message table.
i want to get all the messages between the authenticated user and the receiver.
here are the tables and the models:
the users table and model are obvious.
Message model :
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Message extends Model
{
protected $fillable = [
'parent_id', 'message', 'type','status',
];
public function user_messages(){
return $this->hasMany('App\UserMessage');
}
public function users(){
return $this->belongsToMany('App\User','user_messages','message_id','sender_id')->withTimestamps();
}
}
User_message model :
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class UserMessage extends Model
{
protected $fillable = [
'message_id', 'sender_id', 'receiver_id','type','seen_status','deliver_status',
];
public function message(){
return $this->belongsTo('App\Message');
}
}
Message table :
* #return void
*/
public function up()
{
Schema::create('messages', function (Blueprint $table) {
$table->id();
$table->integer('parent_id')->nullable();
$table->longText('message')->nullable();
$table->integer('type')->default(1)->comment('1 : message , 2 : file');
$table->integer('status')->default(1);
$table->timestamps();
});
}
User_message table :
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('user_messages', function (Blueprint $table) {
$table->id();
$table->integer('message_id');
$table->integer('sender_id');
$table->integer('receiver_id');
$table->integer('type')->default(0)->comment('1 : groupe message , 0 : personal message');
$table->integer('seen_status')->default(0)->comment('1 : seen');
$table->integer('deliver_status')->default(0)->comment('1 : delivered');
$table->timestamps();
});
}
so all i want to know is how the logic inside the controller function will be.
I found the solution :
public function getMessages($id, $ids){
$final_messages_list = array();
$auth_id = $id;
$friend_id = $ids;
$messages = UserMessage::where('sender_id',$auth_id)->where('receiver_id',$friend_id)->orderby('created_at','desc')->get();
foreach($messages as $message){
$final_messages_list[] = $message->message;
}
return response()->json([
'status' => 200,
'messages' => $final_messages_list,
]);
}
I want to have fields created_by,updated_by and deleted_by and want to update these fields automatically. created_by,updated_by is working but deleted_by is not working.i am using an observer to perform this task. When i use dd($model) in deleting function in observer it shows the collection or values but the deleted_by is not updating.
My model
namespace App\Model;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use App\Observers\UserIdFinderObserver;
class supplier extends Model
{
use SoftDeletes;
protected $fillable = [
'name', 'address', 'contact','contact_person_name','country','email'
];
public static function boot()
{
parent::boot();
$class = get_called_class();
$class::observe(new UserIdFinderObserver());
}
}
my migration file
public function up()
{
Schema::create('suppliers', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('contact_person_name');
$table->string('country')->nullable();
$table->text('address')->nullable();
$table->string('contact')->nullable();
$table->string('email')->nullable();
$table->string('created_by')->nullable();
$table->string('updated_by')->nullable();
$table->string('deleted_by')->nullable();
$table->softDeletes();
$table->timestamps();
});
}
My delete function in controller
public function destroy(supplier $supplier)
{
try{
$supplier->delete();
return redirect()->route('supplier.index')->with('success', 'Supplier is deleted successfully');
}catch(Exception $e){
return redirect()->back()->withErrors($e->getMessage());
}
}
My Observer
namespace App\Observers;
class UserIdFinderObserver
{
private $userID;
public function __construct(){
$this->userID = auth()->id();
}
public function saving($model)
{
$model->created_by = $this->userID;
}
public function updating($model){
$model->updated_by = $this->userID;
}
public function creating($model)
{
$model->created_by = $this->userID;
}
public function deleting($model)
{
$model->deleted_by = $this->userID;
}
}
I've a problem in using database relationships together with Laravel module.
for example:
I've User module & Profile Module
I've One-to-One relation between user & profile (in 2 separated modules)
I need to get profile information when I have user data (example: $user->profile)
But I think because of creating relation between two modules, I cannot access to this relation.
My received error:
"message": "SQLSTATE[42S02]: Base table or view not found: 1146 Table 'user.profiles' doesn't exist (SQL: select * from profiles where profiles.user_id = 2 and profiles.user_id is not null limit 1)",
"exception": "Illuminate\Database\QueryException",
User Module/Entities/User.php
<?php
namespace Modules\User\Entities;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Modules\VofourCourse\Entities\Profile;
class User extends Authenticatable
{
use HasFactory;
protected $connection = 'user';
protected $guarded = [];
protected $hidden = [
'password',
'remember_token',
];
protected $casts = [
'email_verified_at' => 'datetime',
];
public function profile()
{
return $this->hasOne(Profile::class);
}
}
Profile Module/Entities/Profile.php
<?php
namespace Modules\Profile\Entities;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\SoftDeletes;
use Modules\User\Entities\User;
use RichanFongdasen\EloquentBlameable\BlameableTrait;
class Profile extends Model
{
use HasFactory, SoftDeletes, BlameableTrait;
protected $guarded = [];
public function user()
{
return $this->belongsTo(User::class);
}
}
Profile Module/Controller/ProfileController.php
<?php
namespace Modules\Profiole\Http\Controllers;
use Illuminate\Routing\Controller;
class ProfileController extends Controller
{
public function showProfile()
{
$user = auth('api')->user();
return $user->profile;
}
}
Profile migration
Schema::create('profiles', function (Blueprint $table) {
$table->id();
$table->foreignId('user_id')->onDelete('cascade');
$table->string('whatsapp_mobile', 15)->unique();
$table->string('phone', 15)->unique();
$table->string('national_code', 10)->nullable();
$table->string('postal_code', 10)->nullable();
$table->text('address')->nullable();
$table->string('job_title')->nullable();
$table->foreignId('city_id')->nullable();
$table->string('father_name')->nullable();
$table->enum('marital_status', ['married', 'single', 'widow', 'divorced', 'unknown'])->default('married');
});
User migration
Schema::connection(config('modules.connections.user_database'))->create('users', function (Blueprint $table) {
$table->id();
$table->string('firstname')->nullable();
$table->string('lastname')->nullable();
$table->string('email')->unique()->nullable();
$table->string('vofour_id' , 10)->nullable();
$table->string('username', 20)->nullable();
$table->timestamp('email_verified_at')->nullable();
$table->string('password')->nullable();
$table->date('birth_date')->nullable();
$table->enum('gender', ['male', 'female'])->nullable();
$table->string('mobile', 15)->unique();
$table->enum('status', ['active', 'inactive'])->default('active');
$table->rememberToken();
});```
thanks a lot for your helps & guidance
You've a typing error in your relationship. The error states there should be a relation profiles where as from your code there's a profile.
public function profile()
{
return $this->hasOne(Profile::class);
}
What you can do is return user->with('profile') which will return the user with it's relational details. I.e.
<?php
namespace Modules\Profiole\Http\Controllers;
use Illuminate\Routing\Controller;
class ProfileController extends Controller
{
public function showProfile()
{
$user = auth('api')->user();
return $user->with('profile');
}
}
Also update your profiles migration line where user_id is written from:
$table->foreignId('user_id')->onDelete('cascade'); to $table->foreignId('user_id')->constrained('users');.
This will link up the user_id as a foreign key to users table id. and return the correct collection of users with their profiles.
hi i have this relationships with these 3 models
Customers
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Customers extends Model
{
public $primaryKey = 'id';
protected $fillable = [
'contr_nom',
'contr_cog',
'benef_nom',
'benef_cog',
'email',
'polizza',
'targa',
'iban',
'int_iban',
'cliente',
];
public function claims()
{
return $this->hasMany(Claims::class);
}
public function refunds()
{
return $this->hasManyThrough(Refunds::class, Claims::class);
}
}
Claims
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Claims extends Model
{
public $primaryKey = 'id';
protected $fillable = [
'dossier',
'date_cla',
];
public function refunds()
{
return $this->hasMany(Refunds::class);
}
public function customers()
{
return $this->belongsTo(Customers::class,'customers_id');
}
}
and Refunds
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Refunds extends Model
{
public $primaryKey = 'id';
protected $fillable = [
'date_ref',
'status_ref',
'disactive',
];
public function services()
{
return $this->belongsToMany(Services::class)
->withPivot(['services_id','services_amount','services_status']);
}
public function claims()
{
return $this->belongsTo(Claims::class,'claims_id');
}
}
i have this in the controller (part of the code)
$data = Claims::with(array('customers'=>function($query){
$query->select('id','contr_nom','contr_cog','targa','email','gcliente');
}))->get();
it works, i can get customers information (parent table) for each dossier ( i put in a datatables)
But i cannot insert another filter based on Refunds table.
I need to show only dossiers where
['status_ref', '>',4]
the problem is that status_ref is in Refunds table
i tried to do somthing like this but no works
$data = Claims::with(array('customers'=>function($query){
$query->select('id','contr_nom','contr_cog','targa','email','gcliente');
}))->refunds()
->where('status_ref', '>',4)
->get();
I cannot understand why....
Thx
You have to use whereHas like:
$data = Claims::with(array('customers'=>function($query){
$query->select('id','contr_nom','contr_cog','targa','email','gcliente');
}))
->whereHas('refunds', function (Builder $query) {
$query->where('status_ref', '>', 4);
})
->get();