yuhha
yuhha

Reputation: 1

How to get sum value from different table based id relation laravel then display on view?

I get stuck on this and i newbie on laravel :( I can't display list of user score test. This is my code :

My User Model :

class User extends Authenticatable
{
    use Notifiable;

    protected $fillable = [
        'name', 'username', 'email', 'password',
    ];

    protected $hidden = [
        'password', 'remember_token',
    ];

    protected $casts = [
        'email_verified_at' => 'datetime',
    ];

    public function test()
    {
        return $this->hasOne('App\Test');
    }
}

My Test Model :

class Test extends Model
{
    protected $fillable = [
        'user_id', 'test_a', 'test_b',
    ];

    public function user()
    {
        return $this->belongsTo('App\User');
    }
}

My Controller :

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\User;
use App\Test;
use DB;

class HomeController extends Controller
{
    public function index()
    {
        $users = User::get();
        $scores = Test::with('user')
            ->value(DB::raw("SUM(test_a + test_b)"));

        return view('home', compact('users','scores'));
    }
}

My home View :

                    <table>
                        <tr>
                            <th>Name</th>
                            <th>Total Score</th>
                        </tr>
                        @foreach($users as $user)
                        <tr>
                            <td>{{ $user->username }}</td>
                            <td>{{ $scores }}</td>
                        </tr>
                        @endforeach
                    </table>

The problem is i can't display list of user and total score each user. I get eror. Anyone can help me with this??

Upvotes: 0

Views: 21

Answers (1)

Ahmar Arshad
Ahmar Arshad

Reputation: 497

You have to use closure to apply query on eloquent relationship. So

In HomeController.php

public function index()
{
    $users = User::with(['test' => function($query){
        $query->select('*', DB::raw("SUM(test_a + test_b) as scores"))
    }])->get();

    return view('home', compact('users'));
}

And in view

<table>
    <tr>
        <th>Name</th>
        <th>Total Score</th>
    </tr>
    @foreach($users as $user)
    <tr>
        <td>{{ $user->username }}</td>
        <td>{{ $user->test->scores }}</td> <!-- getting scores of user -->
    </tr>
    @endforeach
</table>

Upvotes: 1

Related Questions