I am familiar with the love of Eloquent among the laravel community but sometimes, sometimes it's better to go for raw queries. It saves you a lot of time and trouble.

Trust me, it's hard to digest but is true.

Before diving into the details of this approach, for those of you who would like to use a Laravel Package instead of doing all the mentioned things manually. I created the package for them. You can install the package from GitHub here.

Please Show your support by staring the repo.

Let's consider a case where the following query is a complex one.

select count(id) from users where admin_id = 2

Step one (Creating required directory)

Create a queries directory in storage. storage/queries, you can create further sub-directories as per requirement.

Step Two (Adding helper method)

Add the following method to your helper methods.

if (!function_exists('getQuery')) {
    /**
     * @param $queryName
     * @param null $data
     * @return array|false|string|string[]
     */
    function getQuery($queryName, $data = null)
    {
        $query = file_get_contents(storage_path('queries/' . $queryName . '.sql'));

        if ($data) {
            foreach ($data as $key => $value) {
                $query = str_replace($key, $value, $query);
            }
        }

        return $query;
    }
}

Step Three (Calling the query)

Once the directory and helper function are in place all you have to do is create SQL query files in the storage/queries directory

say, storage/queries/admin.users.sql

containing the query,

select count(id) from users where admin_id = adminId

Please note, that the dynamic IDs are replaced with a variable name.

Call the query with the helper function as follows.

use Illuminate\Support\Facades\DB;

/**
 * @return array
 */
public function adminUsers(): array
{
    return DB::select(getQuery('admin.users', [
        'adminId' => auth()->id()
    ]));
}

In this way, you can get any complex query data, without going through the trouble of Eloquent.

Feel free to provide us with your review and feedback in the form of comments.