When defining an accessor you can access to original value using this to skip mutator :
$model->getRawOriginal('name');
Useful if your tables have prefix defined in config.database.[db_connection].prefix
:
$projectTableName = with(new App\Models\Project)->getTable();
$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)));
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];
}
}