Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

nikoslykos's avatar

How to query many to many relationship using eloquent.

Hey guys, i need some help with something. I'll provide the code needed first.

SalesController


<?php

namespace App\Http\Controllers\Sales;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use App\Models\Sales;
use App\Http\Resources\Sales as SalesResource;

class SalesController extends Controller
{
    
public function show($id)
{
$user = Auth::id();
$invoice =Sales::findOrFail($id)->products_in_sales()->where('sales.id',$id)->where('sales.user_id',$user)->first();
       
return new SalesResource($invoice); 
}

Sales Model


<?php

namespace App\Models\Sales;

use Illuminate\Database\Eloquent\Model;

class Sales extends Model 
{

    protected $table = 'sales';
    public $timestamps = true;
    protected $fillable = array('id', 'client_id', 'user_id', 'invoice_number', 'type');

    public function products_in_sales()
    {
        return $this->belongsToMany('App\Models\Products','products_sales','invoice_id','product_id');
    }

}

Sales Resource


<?php

namespace App\Http\Resources\Sales;

use Illuminate\Http\Resources\Json\JsonResource;

class Sales extends JsonResource
{

    public function toArray($request)
    {
        return [
            'id' => $this->id,
            'client_id' => $this->client_id,
            'user_id' => $this->user_id,
            'invoice_number' => $this->invoice_number,
            'type' => $this->type
        ];
    }
}

Firstly laravel acts only as API server and i use the api responses through angular.

I have 3 tables : Sales , Products and a pivot table products_sales. In products table i save each product with the sale_id so i need to bind one sale with the products. I have set the relation in my sales_model but i dont understand how exactly i can do that. What i have wrote on sales controller, does it seem correct? or there is a better way?

0 likes
4 replies
nikoslykos's avatar

My problem is i can't find how to do that with a resource..

jlrdw's avatar

Have you done a dd or print_r at various points to see if data is indeed there.

Cronix's avatar

Your query is only getting this far: $invoice =Sales::findOrFail($id) findOrFail executes the query, so that needs to go last.

Please or to participate in this conversation.