Md. Rashedul Hasan Md. Rashedul Hasan - 22 days ago 6
MySQL Question

Find many columns values total in laravel blade Laravel 5.5

I have a table named 'courses'. I want to show 'first_line','second_line' and 'third_line' points total for each course for each user who purchased one or more courses from my courses table,individually.
Here is my 'courses' table-
courses

And my output is-

1
2

I tried something like bellow in my controller, but I could not pass the '$totalPoints' variable to blade to show the totalpoints, I think this is the wrong way. What should I do for getting the right result? Please someone help me-

public function showCourses(){
if ($user_name = Sentinel::getUser()->user_name) {
$mycourses = DB::table('users')
->join('buy_courses', 'users.user_name', '=', 'buy_courses.user_name')
->join('courses', 'courses.course_name', '=', 'buy_courses.course_name')
->select('buy_courses.course_name','courses.amount','courses.first_line','courses.second_line','courses.third_line','buy_courses.user_name')
->where('users.user_name', $user_name)
->get();
//total points for affiliates
$line_points = DB::table('courses')
->select('first_line','second_line','third_line')
->first();

$totalPoints = $line_points->first_line + $line_points->second_line + $line_points->third_line;

}

//dd($totalPoints);

return view('courses.show',['mycourses' => $mycourses],['totalPoints' => $totalPoints]);
}

Answer Source

This is very simple. You can try this after getting all courses in controller:-

public function showCourses(){
        if ($user_name = Sentinel::getUser()->user_name) {
                $mycourses = DB::table('users')
                ->join('buy_courses', 'users.user_name', '=', 'buy_courses.user_name')
                ->join('courses', 'courses.course_name', '=', 'buy_courses.course_name')
                ->select('buy_courses.course_name','courses.amount','courses.first_line','courses.second_line','courses.third_line','buy_courses.user_name')
                ->where('users.user_name', $user_name)
                ->get();
            foreach($mycourses as $key => $getcourse){
                $mycourses[$key]->total_points = $getcourse->first_line + $getcourse->second_line + $getcourse->third_line;
            }

        return view('courses.show',['mycourses' => $mycourses]);
    }

Now you don't need to pass the total Points separately. NOw total points is added in mycourses key. When you print in blade like this-

@foreach($mycourses as $course)
   Course Name : {{$course->course_name}}
   First Line : {{$course->first_line}}
   Second Line : {{$course->second_line}}
   Third Line : {{$course->third_line}}
   Course Fee : {{$course->amount}}
   All Total Points : {{$course->total_points}}
@endforeach

Hope it helps!