Search code examples
phpsqllaraveleloquentlaravel-query-builder

How can i get the same output using the laravel eloquent query builder?


I am trying to convert a legacy app to Laravel. The legacy app is using MYSQLi and I need to convert all the queries to PDO for Laravel but I am stuck.

This is the code in the legacy app:

public static function get_permissions()
{
    $db->query('SELECT ID, Name, Level, Secondary FROM permissions ORDER BY Level');
    $Classes = $db->to_array('ID');
    $ClassLevels = $db->to_array('Level');

    return [$Classes, $ClassLevels];
}

public function to_array($Key = false, $Type = \MYSQLI_BOTH, $Escape = true)
{
    $Return = [];
    if (!is_bool($this->QueryID)) {
        dump($this->QueryID);
        while ($Row = mysqli_fetch_array($this->QueryID, $Type)) {
            if ($Escape !== false) {
                $Row = Arr::display_array($Row, $Escape);
            }
            if ($Key !== false) {
                $Return[$Row[$Key]] = $Row;
            } else {
                $Return[] = $Row;
            }
        }

        mysqli_data_seek($this->QueryID, 0);
    }
}

public static function display_array($Array, $Escape = [])
{
    foreach ($Array as $Key => $Val) {
        if ((!is_array($Escape) && $Escape == true) || !in_array($Key, $Escape)) {
            $Array[$Key] = display_str($Val);
        }
    }

    return $Array;
}
/* the output
$Classes = array:8 [▼
  100 => array:4 [▼
    "ID" => 2
    "Name" => "User"
    "Level" => 100
    "Secondary" => 0
  ]
  150 => array:4 [▶]
  200 => array:4 [▶]
  201 => array:4 [▶]
  202 => array:4 [▶]
  250 => array:4 [▶]
  800 => array:4 [▶]
  1000 => array:4 [▶]

*/

This is what I have done so far in Laravel:

public static function getPermissions()
{
    if (Cache::has('permissions')) {
        return Cache::get('permissions');
    }

    return Cache::rememberForever('permissions', static function () {
        return self::query()
            ->select(['ID', 'Name', 'Level', 'Secondary'])
            ->orderBy('Level')
            ->get()
            ->toArray();
    });
}

I am stuck on the $db->to_array() part as I don't know how to do that within Laravel. Any help would be greatly appreciated.


Solution

  • You can use the keyBy() method on the collection to achieve what you're after:

    public static function getPermissions()
    {
        return Cache::rememberForever('permissions', static function () {
            return self::query()
                ->select(['ID', 'Name', 'Level', 'Secondary'])
                ->orderBy('Level')
                ->get()
                ->keyBy('Level') // <-- This line
                ->toArray();
        });
    }
    

    Also, when using remember or rememberForever with Laravel's cache, the Cache::has(...) and Cache::get(...) is redundant as this will happen in the remember call anyway.