Laravel one to one relationship. Save username from table to another table - php

TLDR: How do I create a relationship from one table to another? For example, I want changes from the user table automatically reflect on to the supplier table? Something like it's just referencing from the user table.
I have this 2 tables
========================
USER table
1. id
2. username
3. password
4. name
========================
and
========================
SUPPLIER table
1. id
2. username
3. name
========================
Every time I add a new user, it should automatically be saved into the supplier table. This is what I did:
function saveUser($postdata) {
$newUser= new \App\UserModel;
$newUser->email = $postdata['email'];
$newUser->password = $postdata['password'];
$newUser->name = $postdata['name'];
$newUser->save();
$this->saveSupplier($postdata['email'], $postdata['name']);
}
function saveSupplier($email, $name) {
$newSupplier = new \App\SupplierModel;
$newSupplier->email = $email;
$newSupplier->name = $name;
$newSupplier->save();
}
You see, it's not in a relationship right. It's just like manually saving into two tables. How do I make the Supplier table dependent on the user table? For example, everytime I make changes in the User table, it will automatically reflect on to suppliers table without having to fire an update method.

One way to achieve this would be to register and event in the boot method of your
User model.
protected static function boot()
{
parent::boot();
static::created(function($user) {
Supplier::create([
'username' => $user->username //or email or whatever you have.
'name' => $user->name
]);
});
}

Do you might be interested in triggers. If you can create triggers you can use them to insert into SUPPLIER every time you insert in USER.
Something like:
CREATE TRIGGER t_reflect_changes_user_supplier
AFTER INSERT
ON USER FOR EACH ROW
BEGIN
-- trigger code
INSERT INTO SUPPLIER (username,name) VALUES new.username,new.name
END;

Related

How to show username from a relationship table in laravel

I have two tables users and tournaments. I have defined the relationships in the model for both as many to many. I have a third pivot table where user registered to tournament are stored. In this table i want to store the username of the user as well. Here is my storing function
$tournament->users()->syncWithoutDetaching([auth()->id()]);
$request->session()->flash('success', 'You have joined the tournament');
return back()->with('tournament', $tournament);
What can i add so i can store the username aswell?
Thanks in advance
To Store User name In pivot table just create an extra column named user_name in pivot table and you can save it like below
$userId = auth()->id();
$userName =auth()->user()->name;
$tournament->users()
->syncWithoutDetaching([$userId=>['user_name'=>$userName]]);
$request->session()->flash('success', 'You have joined the tournament');
return back()->with('tournament', $tournament);
To Fetch username as well when calling the relation add withPivot() to your Model
public function relationName(){
return $this->belongsToMany(Model::class)->withPivot('user_name');
}
Update
$userName = auth()->user()->name ; // Instead name get the value you want from table column name
check the documentation

How to insert id from both tables into pivot table using laravel query builder

I have three tables in database
users
locations
location_user (columns: user_id, location_id)
I'm fetching records from locations table in multiple-drop-down field of user registration form. While filling form user has to select value from drop-down and then submit.
After submitting the form I want to insert data into users table. At the same time I also want to insert id from users table into user_id column of location_user and selected value of locations from drop-down of user registration form into location_id column of location_user table.
I know how to get this to work using eloquent but I as i mentioned in the question I want to know how to deal with this task using query builder of laravel.
Is there any reason to use a pivot table here? If you're going to tie a location to a user then just add a location_id field to the user table and have a one to many relation (location, user). I don't see any reasoning to use pivot table here unless you want a user to have multiple locations.
Anyway if you follow my advice it becomes easier. But with the current table structure, you need to setup relationships in the respective models. Then on form submit, create the user and attach the location to the user.
User model
public function locations()
{
return $this->belongsToMany('App\Location');
}
Location model
public function users()
{
return $this->belongsToMany('App\User');
}
Controller
$user = User::create($request->all());
$user->locations()->attach($request->location_id);
you must use this code:
$user = new user;
$user->title = $request->title; // your value
$user->username = $request->username // your value
$user->save();
$user->locations()->attach([1,2]); // or ->attach($location_id);
/// or $user->locations()->sync([1,2])
this is a example for your project when use ORM Eloquent and define relationship in models.
you can attention my example:
model Product
class Product extends Model
{
public function Categories()
{
return $this->belongsToMany('App\Category','product_category','category_id');
}
}
model Category
class Category extends Model
{
public function Products()
{
return $this->belongsToMany('App\Product','product_category','product_id');
}
}
when you want insert in your database you must write this code in your controller
$validated = $request->validated();
$user = Auth::user();
$product = new Product;
$product->title = $request->title;
$product->off_price = $request->off_price;
$product->price = $request->price;
$product->available = $request->available;
$product->user_id = $user->id;
$product->save();
$product->Categories()->attach($request->categories/* this is an array*/);
Here, this creates 3 separate queries using the query builder to get to what you want.
$user_id = DB::table('users')->insertGetId(
['something' => 'something']
);
$location_id = DB::table('locations')->insertGetId(
['something' => 'something']
);
DB::table('location_user')->insert(
['user_id' => $user_id, 'location_id' => $location_id]
);
But Laravel's ORM deals with this, so if you have your models mapped properly, you could do something like this:
$location = $user->locations()->create([
'something' => 'something.',
]);
See here: https://laravel.com/docs/5.4/eloquent-relationships

How to insert data into a pivot table with columns belonging to same model in Laravel?

I have a Block model which is basically for blocked users. It has a target_id and a sender_id, both of which are IDs from the users table. How can I add data to this pivot table when a user wants to block another user? What should my relationship methods look like?
Since both target_id and sender_id are fields from the users table, your relationship must be defined this way.
class User {
public function blocks() {
return $this->belongsToMany('App\User','blocked_users','sender_id','target_id')->withPivot(['id']);
}
public function blockedBy() {
return $this->belongsToMany('App\User','blocked_users','target_id','sender_id')->withPivot(['id']);
}
}
Here blocked_users is the name of the table.
So, to block a user you can do :-
//User who is going to block
$user = User::find($id);
$inputs = [$target_user_id];
$user->blocks()->attach($inputs);
//or you can use,
$user->blocks()->sync($inputs, false);
The false in the above sync is used when the old synced rows are ignored and new ones are attached.
To get the list of users who that particular user has blocked, you can do :-
$user = User::find($id);
$user->blocks;
And to get the list of users who that particular user is blocked by
$user = User::find($id);
$user->blockedBy;
Thanks,

Fetching data from two tables depending upon condition in CakePHP

I have two controllers LeaveApplicationsController and EmployeesController. In LeaveApplicationsController index action I'm displaying leave records of all employees. It is showing fine but what I need is to show only login employees leaves to that employee. I have employee_id as foreign key in leave_applications table. But I am not getting employee_id (which is id) from employees table. I also have users table and each user has one employee associated with it. So when employee is created, before that user is created and newly created user's id is also stored in employees table under unser_id field. So user_id is foreign key in employees table and uniquely identifies the employee.
This is my LeaveApplicationsController.php code:-
public function index()
{
$userId = $this->Auth->user('id'); //gets current user's id
$this->LeaveApplication->recursive = 0;
$leavereqs = $this->set('leaveApplications', $this->Paginator->paginate());
$employeeId = $this->Employee->find('all', array('fields'=>array('id'), 'conditions'=>array('Employee.user_id'=>$userId))); // code for getting emp id
return $this->LeaveApplication->find('all', array('conditions'=>array('LeaveApplication.employee_id'=>$employeeId))); //code for fetching current employee record
}
But this shows error. Please tell me where am I doing it incorrect? I'm also using $uses to load Employee model in LeaveApplicationsController. Thanks.
public function index()
{
$userId = $this->Auth->user('id'); //gets current user's id
$this->LeaveApplication->recursive = 0;
$leavereqs = $this->set('leaveApplications', $this->Paginator->paginate());
$employeeId = $this->Employee->find('list', array('fields'=>array('id'), 'conditions'=>array('Employee.user_id'=>$userId))); // code for getting emp id
return $this->LeaveApplication->find('all', array('conditions'=>array('LeaveApplication.employee_id'=>$employeeId))); //code for fetching current employee record
}
find('all') will return array with index Employee and id
Imp links: find('all'), find('first') and find('list')
http://book.cakephp.org/2.0/en/models/retrieving-your-data.html#find-first
http://book.cakephp.org/2.0/en/models/retrieving-your-data.html#find-all
http://book.cakephp.org/2.0/en/models/retrieving-your-data.html#find-list

Adding a HABTM as a registration in CakePHP

I have Users and Courses.
I have a users table, and a courses table.
I also have a course_memberships table with id |
course_id | user_id
I have the appropriate hasmany relationship
for courses and users to relate to CourseMembership
But I have no idea how to create that relationship using a button on the front end. Something like a public function register() on the Courses controller that would put the Auth User ID in the user_id field, and the course id in the course_id field to form the relationship.
I know it was a wall of text, but I figured a description of the issue may be more helpful than an endless scroll of code.
Can anyone help?
You should create a method to save to the CourseMembership model within the Courses Controller. Something like this would work.
public function register($course_id){
$user_id = $this->Auth->user('id');
$data = array(
course_id => $course_id,
user_id => $user_id;
);
if($this->Courses->CourseMembership->save($data)){
$this->Session->setFlash('Registered');
$this->redirect($this->referer());
}
else{
$this->Session->setFlash('Could not register');
$this->redirect($this->referer());
}
}
This way, when people go to /Courses/register/1, it would register them for the course with the ID of 1.
Then when you do a find on the User, the data would be in $user['CourseMembership']

Categories