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

moglong's avatar

Translate raw SQL into Eloquent

Dear Expert,

Pardon my english

how to translate

SELECT * FROM `facilities` ORDER BY SUBSTRING( `product_id` FROM 1 FOR 1 ) ASC, name ASC

to Eloquent???

My code

Product Model

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Product extends Model
{

    protected $table = 'products';

    protected $primaryKey = 'id';

    protected $fillable = ['name', 'sortdesc', 'fulldesc', 'bookinglink', 'image', 'category'];

    public function Facility(){
      return $this->hasMany('App\Facility')->IN THIS SECTION THAT ELOQUENT WILL BE USE;
    }
}

Facility Model

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Facility extends Model
{
    protected $table = 'facilities';
    protected $primaryKey = 'id';
    public function Product(){
      return $this->belongsTo('App\Product');
    }
}

And View

@foreach ($product->Facility as $key => $value)

if we use the RAW SQL Query

SELECT * FROM `facilities` ORDER BY SUBSTRING( `product_id` FROM 1 FOR 1 ) ASC, name ASC

it looks like this:

| product_id | name
-------------------------------------------
|     1      | 23 sqm metre private balcony
|     1      | 4 sqm
|     1      | 43” TV
|     1      | Air Conditioning
|     1      | Bath Tub
|     1      | Bathroom with hot water
|     1      | Bunk Bed
|     1      | Cable TV
|     1      | DVD Player
|     1      | Fridge
|     1      | Hairdryer
|     1      | Kettle
|     1      | Laptop Size Safe
|     1      | Located on 2nd Floor
|     1      | Queen Bed
|     1      | Shower
|     1      | Sofa
|     1      | Surfboard Rack
|     1      | Universal Power Outlet with USB
|     1      | View of Sea and Mt Agung
|     2      | 23 sqm metre private balcony
|     2      | 34 sqm
|     2      | 43” TV

Thank you for your time

0 likes
1 reply
Cinek's avatar
Cinek
Best Answer
Level 6

Try this:

Facility::orderByRaw("substring('product_id' from 1 for 1)")->orderBy('name','ASC')->get();

Please or to participate in this conversation.