Skip to content

Instantly share code, notes, and snippets.

@rseon
Last active December 4, 2022 23:08
Show Gist options
  • Save rseon/ca31b62622eab10713b035f89616f9e9 to your computer and use it in GitHub Desktop.
Save rseon/ca31b62622eab10713b035f89616f9e9 to your computer and use it in GitHub Desktop.
Laravel cheatsheet

Laravel cheatsheet

Original Eloquent attribute

When defining an accessor you can access to original value using this to skip mutator :

$model->getRawOriginal('name');

Get model table name

Useful if your tables have prefix defined in config.database.[db_connection].prefix :

$projectTableName = with(new App\Models\Project)->getTable();

QueryBuilder sub-query

$subQuery = DB::table($companyTable, 'c')
   ->select(DB::raw('c.id as company_id, p.id as project_id'))
   ->join($projectTable. ' as p', 'p.id', '=', 'c.project_id')
   ->whereNull('c.deleted_at')
   ->whereNull('p.deleted_at')
   ->groupBy('c.id')
   ->groupBy('p.id')
   ;

return DB::table(DB::raw("({$subQuery->toSql()}) as p1"))
    ->select(DB::raw('p1.company_id, COUNT(p1.project_id) as project_count'))
    ->groupBy('p1.company_id')
    ->get();

Similar to plain SQL :

$query = "
  select p1.company_id, COUNT(p1.project_id) as project_count
  from (
      select c.id as company_id, p.id as project_id
      from `{$companyTable}` as `c`
      inner join `{$projectTable}` as `p` on `p`.`id` = `c`.`project_id`
      where `c`.`deleted_at` is null and `p`.`deleted_at` is null
      group by `c`.`id`, `p`.`id`
  ) as p1
  group by `p1`.`company_id`
";

return collect(DB::select(DB::raw($query)));

PHP Human file size

Laravel tip : add it in your custom helpers

if (!function_exists('human_filesize')) {
    /**
     * @param int
     * @param int
     * @return string
     * @link https://gist.github.com/gladx/62fa307eb65586b6dbaaad75273c653d
     */
    function human_filesize($bytes, $decimals = 2)
    {
        if ($bytes < 1024) {
            return $bytes . ' B';
        }

        $factor = floor(log($bytes, 1024));
        return sprintf("%.{$decimals}f ", $bytes / pow(1024, $factor)) . ['B', 'KB', 'MB', 'GB', 'TB', 'PB'][$factor];
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment