How to find all id pivot from pivot table? (laravel 5.3) - php

I have a pivot table. The name is users_banks table. The table have field id, user_id, bank_id, status, account_name and account_number
Now, the pivot have 3 records
I display contain from pivot table using code like this :
$user_id = auth()->user()->id;
$user = $this->user_repository->find($user_id);
$account = array();
foreach($user->banks as $bank) {
$account[] = $bank;
}
dd($account);
The result display all record in the form of array. There exist value of field user_id, bank_id, status etc. But I don't find value of id
How can I find id from pivot table?

If the relationship is defined correctly you can use:
$bank->pivot->id
but make sure the user belongsToMany(Bank::class) and the bank belongsToMany(User::class) or else it wont work.

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

eloquent: check for existing data in pivot table (primary key + extra column)

I have a pivot table with an extra column. I need to check if pair of data exists in this table prior to updating the extra column.
There are two orders of problems here, first how can I do this check?
I tried something like
If ($user->pivot_table->contains($key, '&&', $extra_column)){}
to no avail.
Second, how do you update the extra column in the pivot ?
// this what worked for me:
$user = Auth::user();
$key = $request->input('key');
$extra_column = $request->input('extra_column');
if (count($user->groups()->where('key', $key)->where('extra_column', $extra_column)->first())){
// fails (data exists already)
}else{
//update pivot
$user->groups()->updateExistingPivot($key, ['extra_column' => $extra_column]);
}

Search in other table?

I have a maintenance table with the following fields: id, car_id, type, and name.
How do I get list of entries from maintenance table where type = 'car wash' but only with model_id = 5?
model_id field are in the car table. Car table with the following fields: id, model_id, engine_size, and color.
How can I use Maintenance::where to get list of entries with matching model_id in a car table? There is car_id in a maintenance table which link with car table.
Do I need to do something like this: ?
return Maintenance::where('type', 'car_wash')->where(function($query) {
// get a list a maintenance where model_id = 5 in a car table
});
Assuming you've already defined cars() relation on your Maintenance model you could try something like that:
$model_id = 5;
$type = 'car_wash';
return Maintenance::whereHas('cars',function($query) use($model_id,$type) {
$query->where('model_id',$model_id)->where('type',$type);
})->get();
Update for further question (skip if $model_id = 0):
return Maintenance::whereHas('cars',function($query) use($model_id,$type) {
if($model_id!=0){
$query->where('model_id',$model_id);
}
$query->where('type',$type);
})->get();
I did not tested it but it should work, otherwise let me know

Laravel 5 - how to perform left join on same table

In my application, there's two tables at the moment: users and employees. The latter is simply a profile table for the boilerplate users table that ships with Laravel.
I have two foreign keys inside of employees, one is user_id that points to id on users table. So basically, the profile data of the registered user. The second foreign key in employees is manager_id. That is the id of the person who is the manager of an employee. Some users are managers and have a blank manager_id field.
I want to retrieve the row from my Employee model where the user_id matches the manager_idand then send them all to my view, where they will see the first_name and last_name of the manager. At the moment I see the manager ID instead of their name.
Sample LeftJoin =>
DB::connection('testing')->table('table1 as t1')
->select('t1.column, t2.column')
->leftJoin('table2 as t2','t2.client_id','=','t1.id')
->get();
Try some thing like this:
$users = DB::table('users t1')
->join('users t2', 't1.id', '=', 't2.user_id')
->select('your column list')
->get();
// here we are creating 2 aliases for users table which make it self join
In your Employees model add the following method:
public function manager()
{
return $this->hasOne('App\User', 'id', 'manager_id');
}
You can then get the name of the Manager like this:
$employee = \App\Employee::find(1);
$manager = $employee->manager()->first();
$manager_name = $manager->name;

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

Categories