Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

jhutto's avatar

Adding Columns of row in Query Builder

I need to create a query to sum items in a row in query builder. Here is my current query in laravel

$SOMASRegistrations = \App\SOMASRegistration::where('CourseID', '=',  $course_id)
        ->join('somascourseregistrationstatus', 'somascourseregistrations.StatusID', '=', 'somascourseregistrationstatus.id')
        ->get();

I need to add three columns within the query and output as another column. Here is the mysql statement that works with the database

SELECT * , (ClassFee + HomeOfficeFee + MaterialsFee ) AS TotalFee FROM somascourseregistrations WHERE 1

I have tried this but it totals all the rows. I need the fields to be total only by each row.

$SOMASRegistrations = DB::table('somascourseregistrations') ->join('somascourseregistrationstatus', 'somascourseregistrations.StatusID', '=', 'somascourseregistrationstatus.id') ->select(DB::raw('sum(ClassFee+HomeOfficeFee+MaterialsFee) AS TotalFee')) ->where('CourseID', $course_id) ->get();

I couldn't find anything that talked about adding columns in a row in laravel Thanks for your help.

0 likes
2 replies
D9705996's avatar
D9705996
Best Answer
Level 51

You could use a raw expression and add a select

App\SOMASRegistration::where('CourseID', '=',  $course_id)
  ->addSelect(DB::raw('(ClassFee + HomeOfficeFee + MaterialsFee ) AS TotalFee'))
  ->get();

I've not tried the code above but from docs should work

https://laravel.com/docs/5.7/queries#raw-expressions

Please or to participate in this conversation.