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

jhutto's avatar

Converting mysql to laravel query

I have a mysql query that I can not figure out how to translate into Laravel query in controller

The 355 will be a variable as soon as I can get this to run.

SELECT somascourseregistrations.id, `CourseID`, `StudentID`, `StatusID`, `TA`, `DropDate`, `TuitionType`, (`ClassFee`+`HomeOfficeFee`+`MaterialsFee`) AS TotalTuition,
(SELECT SUM(`PaymentAmount`) AS TotalPayments FROM `somasstudentclasspayments` WHERE somasstudentclasspayments.RegistrationID = somascourseregistrations.id) TotalPayments
FROM `somascourseregistrations` WHERE somascourseregistrations.CourseID = 355
0 likes
4 replies
cemcminn's avatar

Why would you not want to execute something that detailed as a stored procedure?

Example:

DB::select('exec my_stored_procedure(?,?,..)',array($Param1,$param2));
1 like
jhutto's avatar

I finally found some searches that lead me in the right direction.

$Registrations = DB::table('somascourseregistrations')
                ->select('somascourseregistrations.id', 'CourseID', 'TuitionType', 'FirstName', 'LastName',
                    DB::raw("(SELECT (ClassFee + HomeOfficeFee + MaterialsFee)                                
                                GROUP BY somascourseregistrations.id) as TotalTuition"),
                    DB::raw("(SELECT SUM(PaymentAmount) FROM somasstudentclasspayments
                                WHERE somasstudentclasspayments.RegistrationID = somascourseregistrations.id
                                GROUP BY somascourseregistrations.id) as TotalPayments"))
                ->join('students', 'students.id', '=', 'somascourseregistrations.StudentID')                
                ->where('CourseID', $courseid)
                ->orderby('LastName')
                ->get();

I'm still really new... But I will look at the stored procedures you are referring too. Can you give me some links to check out?

cemcminn's avatar
cemcminn
Best Answer
Level 2

Do you maintain your own database? I assume so if you wrote a query like that :-)

Generically, stored procedures are objects inside your database that allow you to name and run queries over and over without having to type them each time.

Here is a good generic page to get you started with what you should look into for learning how to write them:

https://www.w3schools.com/sql/sql_stored_procedures.asp

Note that each database engine has its own syntax for creating a stored proc so you will have to look at the documentation for your specific instance.

Database management tools like HeidiSQL have a sort of wizard that keeps you from having to create procs by typing the whole thing.

jhutto's avatar

Perfect.. Thanks cemcminn... Yes.. I'm maintaining the database. I'm new to mysql.. so this is exactly what I needed.

1 like

Please or to participate in this conversation.