Last active
February 22, 2025 19:29
-
-
Save nullthoughts/636ed286f56b105e5a409145c82ddd5d to your computer and use it in GitHub Desktop.
Convert Laravel Scout query to Eloquent query (Macro)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\Providers; | |
use Illuminate\Support\ServiceProvider; | |
use Laravel\Scout\Builder; | |
class MacroServiceProvider extends ServiceProvider | |
{ | |
/** | |
* Register macros. | |
* | |
* @return void | |
*/ | |
public function register() | |
{ | |
Builder::macro('toEloquent', function () { | |
$ids = $this->get()->pluck('id'); | |
$order = $ids->implode(','); | |
return $this->model::whereIn('id', $ids) | |
->orderByRaw("FIELD(id, $order)"); | |
}); | |
} | |
/** | |
* Bootstrap services. | |
* | |
* @return void | |
*/ | |
public function boot() | |
{ | |
// | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage