laravel Many Records to One single record....but how? - laravel

I have two tables, one is Users and the other is Loans. These have one to many relationship between them. One user can have many loans and one loan belongs to one User.
Now I want to get the user from the list of loans.
Loan::where('user_id', $user)->get()
This give me repeated array of sample user associated to the multiple loans. But I want to get only a single record, like many loans associate to one user.

I assume you already set up relationships between User & Loan Models
// App\User
public function loans() {
return $this->hasMany('App\Loan');
}
// App\Loan
public function user() {
return $this->belongsTo('App\User');
}
Get user from the list of loans
$user = Loan::where('user_id', $id)->first()->user;
// eager loading version
$loansWithUsers = Loan::with('user')->where('user_id', $id)->get();
Loans associate to one user
$loans = User::findOrFail($id)->loans;
// eager loading version
$userWithLoans = User::with('loans')->findOrFail($id);

For what I understand in your question, you want to get the user together with it's loan right ? Your query should like this.
$user_loans = User::with('loans')->where('id', $user_id)->get();
Get the user informations from loan table
Loan::where('user_id', $user_id)->with('user')->get()
Ge the users from loans table depends on brach id
Loan::where('branch_id', $branch_id)->with('user')->get();

Related

Laravel: Load only pivot additional columns without relation

I have the following structure:
Charge
id
amount
created_at
..
Payment
id
amount
created_at
..
and a pivot table charge_payment, since one charge can be covered partially by multiple payments.
charge_payment
charge_id
payment_id
amount
The amount column on the pivot table defines the amount that the given Payment covers for the Charge.
And I need to get only the "paid" amount for a Payment.
I have the following models:
// Charge.php
class Charge extends Model
{
public function payments()
{
return $this->belongsToMany('App\Payment')->withPivot('amount');
}
}
// Payment.php
class Payment extends Model
{
public function charges()
{
return $this->belongsToMany('App\Charge')->withPivot('amount');
}
}
I want to be able to get only the paid amount with:
$payment = Payment::find(..);
$paid_amount = $payment->charges->sum('pivot.amount');
However, with this approach the related models are loaded from the database and I won't be needing them.
Is there a way to load only the additional pivot column without the related models?
Thank you very much!
Firstly, if one Payment can be always related only to one Charge, I would advise you to change the relationship from many-to-many to one-to-many (it will be just more correct and simpler).
Than you can simple use aggregate function (in your case withSum) which will return you only resulting values without relationship Models.
$payment = Payment::withSum('payments', 'amount')->find(..);
{{ $payment->payments_sum_amount }}

How to limit access from pivot table? Laravel

I have tables:
user
id
name
companies
id
name
company_user
company_id
user_id
Tables has Many To Many relationships.
As it complicated relationship for me, I can't find way how to make this limit, when user can see companies that was created by this user. (probably not well experienced)
Now I have this, but user can see any company
CompanyController:
public function show($company_id)
{
$company = Company::where('id', $company_id)->firstOrFail();
return view('company.settings', compact('company'));
}
So tip me please how to make user can see only companies created by this user.
You can do this:
public function show($company_id)
{
$company = auth()->user()->companies()->findOrFail($company_id);
return view('company.settings', compact('company'));
}
It will scope the company to the currently logged in user (through the many-to-many relationship on the User model). If none is found, it will return 404.
Since it many to many relation, you can map one company to many users, also map one user to many companies. Check if you have not mistakenly assign the company to many user
Also the above code can be written the way
public function show($company_id)
{
$company = Company::findOrFail($company_id);
return view('company.settings', compact('company'));
}

Eloquent relationship for multiple table

I am working in laravel5.4. I have created four table as ticket, users, and company. Here, I have stored users id in ticket table. And stored company id in users table.
Here, I want to show ticket's user name with that users company name.
Here, I have create relation for it that looks like below.
Ticket model :
public function requesters(){
return $this->belongsTo('App\User','requester_id');
}
Here requester_id is who create ticket.
Users model :
public function company()
{
return $this->belongsTo('App\Models\Admin\Company');
}
Company model :
public function Users()
{
return $this->hasOne('App\Users');
}
Here, I have written query to get users information that looks like below.
Ticket::with('requesters')->orderBy('subject','asc')->paginate(10);
Now, I want to fetch company information or request_id So what changes should I have to do in this query to fetch company info along with ticket and users ?
If you want to to Eager load multiple relationship you can put them all in single with like this:
Ticket::with('requesters','requesters.company')->orderBy('subject','asc')->paginate(10);
but if you load nested relationship you can use shorter notation - you can omit parent relationship, so it's enough to use here:
Ticket::with('requesters.company')->orderBy('subject','asc')->paginate(10);
Try this, it should work for this case:
Ticket::with('requesters')
->with('requesters.company')
->orderBy('subject','asc')->paginate(10);

Laravel relationship between two tables

I'd like your input on this.
I have a Customer_table with a field name. I have another table called Reservation_table with a Customer_name field.
How can I relate them in such a way that I'd see all the bookings by the specific customer?
In Reservation_table you should have a field(foreign key) userid in order ta have a user for each reservation.
You can using primary key - foreign key relationship to relate/join those two tables. Also, instead of having a 'Customer_name' field as your FK referring to 'name' field in 'Customer_table' table, it is better to have an id (unique) generated for each customer; This way you can have an efficient way of uniquely identifying and relating customer across tables; can save space on Database side as well. Hope this helps!
If you want to use eloquent you must first define a relationship.
One reservation belongs to a user. Here is how to define the relationships:
Inside the Reservation model:
public function user()
{
return $this->belongsTo('App/User'); //User model
}
To define the inverse you do the following:
Inside User model:
public function reservations()
{
return $this->hasMany('App/Reservation'); // Reservation Model
}
Now you can do the following in your controller:
$reservations = Auth::user()->reservations;
Now you have all reservations by the currently logged in user.
I am not sure if I got the question right so ask away.

Eloquent - Two Relationships In One?

I've been getting along slowly but surely with Laravel / Eloquent, but am now stumped:
entries Table:
id
user_id
group_id
content
users Table
id
faculty_id
name
group Table:
id
name
faculty Table
id
name
So entries are related to users and groups, and users are related to faculties - I've set up the basic relationships without a problem, and this enables me to find all entries by users from a certain faculty:
Faculty Model:
public function entries()
{
return $this->hasManyThrough('Entry','User');
}
Controller:
Faculty::find(Faculty-ID-here)->entries;
However, I now need to find entries by users that are from a certain faculty AND from a certain group, and I don't know how to write this combination this in Eloquent.
Hope that makes sense! Any suggestions?
Something like:
Entries::whereHas('user', function($q) {
$q->where('faculty_id', $facultyID);
})
->where('group_id', $groupID)
->get();
Assuming you have set up your 'user' relationship.

Resources