Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

264
Views
Laravel Eloquent select only columns from relationship

I have two models InvoiceTotal and MeterTariff with inside the InvoiceTotal model a one to many relationship

public function meter_tariff() {
    return $this->belongsTo(MeterTariff::class);
}

I'm querying all the unique meter_tariff rows based on invoice_id's using the with and distinct functions.

$validatedData = $request->validate([
    'invoice_ids' => ['required', 'array'],
    'invoice_ids*' => ['exists:invoices, id']
]);

$meter_tariffs = InvoiceTotal::with('meter_tariff')
    ->whereIn('invoice_id', $validatedData['invoice_ids'])
    ->distinct('meter_tariff_id')
    ->get();

This is working fine. The result is an array with unique rows based on the meter_tariff_id but I'm getting all the columns from InvoiceTotal and the MeterTariff relationship.

I want to limit the selected columns to id and name from the MeterTariff relationship.

I've tried the following code.

Select:

$meter_tariffs = InvoiceTotal::with('meter_tariff')
    ->whereIn('invoice_id', $validatedData['invoice_ids'])
    ->distinct('meter_tariff_id')
    ->select('meter_tariff:id,name')
    ->get();

Query inside the with:

$meter_tariffs = InvoiceTotal::with(['meter_tariff' => function($query) {
        $query->select('id', 'name');
    }])
    ->whereIn('invoice_id', $validatedData['invoice_ids'])
    ->distinct('meter_tariff_id')
    ->get();

Selection in the with:

$meter_tariffs = InvoiceTotal::with('meter_tariff:id, name')
    ->whereIn('invoice_id', $validatedData['invoice_ids'])
    ->distinct('meter_tariff_id')
    ->get();
over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

You can use pluck to get only the selected columns - id and name from the MeterTariff relationship.

$meter_tariffs = InvoiceTotal::with('meter_tariff')->whereIn('invoice_id', $validatedData['invoice_ids'])->distinct('meter_tariff_id')->get()->pluck('meter_tariff.id', 'meter_tariff.name')
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!