How i get the name of user in this foreach - laravel

This is my controller
$user_rank = Sprintbacklog::select('assign_user_id',DB::raw('count(*) as
jumlah_data'))->where('id_sprint',$id)->where('finish',1)-
>groupBy('assign_user_id')->get();
This is foreach in blade
#foreach($user_rank as $name_and_finish)
<tr>
<td>{{ $name_and_finish->assign_user_id}}</td>
<td><span class="badge">{{ $name_and_finish->jumlah_data }}</span></td>
</tr>
#endforeach

maybe you must join the models, to access the user like
$user_rank = Sprintbacklog::join('users',sprintbacklogs.id_user,'=','users.id')
->where('id_sprint',$id)->where('finish',1)
->select('assign_user_id',DB::raw('count(*) as jumlah_data'))
->groupBy('assign_user_id')
->get();
to access the name in user table, but you need an user id at the table that you want to join with.

Related

Property [name] does not exist on this collection instance. Eloquent Laravel

I have a potentially basic problem for Eloquent. I want to show only the name corresponding with Role of that user. I used the Eloquent Relationship ManytoMany. But I can't get that to work.
I tried point to the name using the $users parameter but this didn't work.
My project has three files such as Role model, StudentController, find_username view.
Thank you.
Role Model:
class Role extends Model
{
protected $fillable = ['id','role_name','role_level','role_note'];
public function users()
{
return $this->belongsToMany('App\User', 'role_users', 'user_id', 'role_id');
}
}
My StudentController:
class StudentController extends Controller
{
public function find_username()
{
$roles = Role::all();
foreach($roles as $role)
{
echo $role->users . '<br>';
}
return view('find_username',['roles'=> $roles]);
}
}
My find_username view:
#extends('master')
#section('content')
<div class="row">
<table class="table">
<thead>
<tr>
<th>ID Role</th>
<th>Role name</th>
<th>Role level</th>
<th>Role note</th>
<th>User name</th>
</tr>
</thead>
<tbody>
#foreach ($roles as $item)
<tr>
<td>{{$item['id']}}</td>
<td>{{$item['role_name']}}</td>
<td>{{$item['role_level']}}</td>
<td>{{$item['role_note']}}</td>
<td>{{$item->users}}</td>
</tr>
#endforeach
</tbody>
</table>
</div>
#endsection
You have many roles. Each of these roles have many users. Your table will be fine as it is to show the name of the role, roll level, and role note, because these are on the looped $item variable individually.
The problem is that while the $item holds those singular fields, the $item->users is another collection of user objects. Which means you have added another dimension onto your table. You might have 1 or 100 users to fit inside that <tr>.
To demonstrate, try this code, specifically adding in all the users names (adding the parameter to each user object in a new loop):
#foreach ($roles as $item)
<tr>
<td>{{$item['id']}}</td>
<td>{{$item['role_name']}}</td>
<td>{{$item['role_level']}}</td>
<td>{{$item['role_note']}}</td>
#foreach($item->users as $user)
<td>
{{$user->name}}
{{$loop->last?"":" | "}} //<-- just to separate names for this test
</td>
#endforeach
</tr>
#endforeach
If you have your models and relations set up correctly, this will show you your users for each role. However, as you can see, this may not be the best way to display this data. You might have dozens of users per role. You may wish to consider making a totally separate table for each role's users. Maybe click on something for the role on this table and bring up a new list or table of those users who have the role.
HTH

Make a sum() of column accessors Laravel

im improving my skills in laravel making a simple challenges web but i stuck on the next problem.
I have the users table with the id, name, mail, etc. The challenges table where i list all the challenges (with columns id, name, body, answer, score) and a third table called "Answers" where i post each try of the users solving a challenge with the columns id, user_id, challenge_id, success (boolean) and score.
Now i'am trying to make a ranking of users with their scores. The problem is to show a sum() of the column 'score' in the table answers where user_id.answers = users.id. So i can get easy the total score for each user.
For now i solved the problem doing this in blade:
#foreach($users as $user)
<tr>
<th>{{ $user->id }}</th>
<td>{{ $user->name }}</td>
<td>Team pindonga</td>
<td>{{ score = DB::table('answers')->where('user_id', $user->id)->sum('score') }} </td> </tr>
#endforeach
works perfectly, but i want to get them by desc score (for now i solved the desc with js but want to get desc order from the eloquent query) and have something like this in the blade:
#foreach($users as $user)
<tr>
<th>{{ $user->id }}</th>
<td>{{ $user->name }}</td>
<td>Team pindonga</td>
<td>{{ $team->score }} </td> </tr>
#endforeach
I was thinking about solve it with accessors doing something like this:
public function getScoreAttribute($value)
{
return $this->groupBy('user_id')->where('user_id', '=', $value)->sum('score');
}
also i have a relationship belongsTo in the answers modle to users and a hasMany in the users to answers. But i'm not sure of how pass the results to blade. Tried in tinker:
>>> \App\Answer::find(1)->score;
=> "3400"
>>> \App\Answer::find(2)->score;
=> "3400"
>>> \App\Answer::find(5)->score;
=> "3400"
allways getting the sum of the id = 1. And with $user->score; in the blade foreach i got a '0'.
Using the relationship with Blade would be {{ $user->answers->sum('score') }}. No accessor needed.
For sorting I would use the sortByDesc collection method.
$users = User::get();
$users = $users->sortByDesc(function ($user) {
return $user->answers->sum('score');
});
I think this is what you're looking for. It takes a while to get used to Eloquent ORM :-)
foreach($users as $user){
print $user->answers->sum('score');
}
https://laravel.com/docs/5.6/queries#aggregates

repeat laravel query result 4 times

i have a question on how to accomplish this task..
how can i repeat the result of a query 4 times and then add a name from other database.. please check this attach image.
i have a database for flight number. and a database for employee name.
this is my code so far
#foreach ( $daily_flight as $d_f)
{{ $d_f->flight_num}}
#endforeach
<table>
#foreach ($csa as $emp)
<tr>
<td>{{ $emp->name }}</td>
</tr>
#endforeach
</table>
Let's imagine that you have 2 tables: flights and employees. Let us also imagine that the flights Table has columns like id, flight_num, etc. Simultaneously; we would also assume that the employees Table contain fields like: id, flight_id, name, etc. Now, working under this arbitrary condition, one can simply write a Query that joins the 2 tables provided there is any kind of JoinCondition that can be established between the 2 - for example: ON employees.flight_id=flights.id.
This would be how to do this from the Controller:
<?php
namespace App\Http\Controllers;
use App\Http\Requests;
use App\User;
use App\Flights; //<== JUST SOME ARBITRARY IMPORTS... MODIFY TO SUIT YOU
use App\Employees; //<== JUST SOME ARBITRARY IMPORTS... MODIFY TO SUIT YOU
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\URL;
class FlightsController extends Controller {
public function flightSchedule(){ //<== ANOTHER ARBITRARY ACTION METHOD
// ASSUME FOR AN INSTANT THAT YOU HAVE 2 TABLES:
// 1.) flights
// 2.) employees
// YOU COULD USE THE join CLAUSE TO JOIN THE 2 TABLES TOGETHER
$flightData = DB::table('flights')
->join('employees', 'employees.flight_id', '=', 'flights.id')
->select('flights.*', 'employee.*')
->groupBy('employees.name')
->get();
// THEN ONCE YOU HAVE YOUR RESULT, IT WOULD BE ONLY
// A MATTER OF LOOPING THROUGH THE RESULT-SET IN THE VIEW SCRIPT
// AND STRUCTURING YOUR MARK-UP AS YOU SEE FIT LIKE THIS:
return view("flights.schedule", array("flightData"=>$flightData));
}
}
Now, in your View Script in our Arbitrary Example; flights/schedule.blade.php
<!-- FICTITIOUS FILE-NAME=> flights/schedule.blade.php -->
<table>
<tr>
<th>FLIGHT NUMBER</th>
<th>ASSIGNED EMPLOYEE</th>
</tr>
<tbody>
#foreach($flightData as $data)
<tr>
<td>{{ $data->flight_num }}</td>
<td>{{ $data->name }}</td>
</tr>
#endforeach;
</tbody>
</table>

Trying to get property of non-object [laravel 5.2]

I'm getting trouble in getting the data from foreign key .
already make relation between 2 tables, but still error gave me this "Trying to get property of non-object"
this is my models
public function tourism()
{
return $this->belongsTo('App\Models\Tourism','tourism_id');
}
this is my controller
$ratings = Ratings::orderBy('rating','desc')->get();
$ratings = $ratings->take(6);
and this is my blade
<tbody>
#if($ratings)
#foreach($ratings as $data)
<tr>
<td class="center">{{$data->id}}</td>
<td class="center">{{$data->tourism_id->nama}}</td>
<td class="center">{{$data->rating}}</td>
</tr>
#endforeach
#endif
</tbody>
thanks
Try
<td class="center">{{$data->tourism->nama}}</td>
EDIT
This situation occurs when you trying get nama property.
But tourism_id it's just an integer, am I right?
First of all,for accessing related model you should use you relationship method(tourism) instead of FK field(tourism_id).
Then you should check are there any related model in tourims() or not. For this purpose i recommend you use ternary operator, so your line should be something like:
<td class="center">{{$data->tourism->first() ? $data->tourism->first()->nama : 'No tourism'}}</td>
Assuming you already have this controller and the model relationship as above:
function ratingsView() {
$ratings = Ratings::orderBy('rating','desc')->get();
$ratings = $ratings->take(6);
return View('rating')->with('ratings',$ratings);
}
In your views,
<tbody>
#if($ratings)
#foreach($ratings as $data)
<tr>
<td class="center">{{$data->id}}</td>
<td class="center">{{$data->tourism()->first()->nama}}</td>
<td class="center">{{$data->rating}}</td>
</tr>
#endforeach
#endif
</tbody>
Make sure your rating table have id, rating as well as tourism_id attributes and your tourism table have name attribute as well as of course there is data in both tables.
You definitely need to check the the availability of the data and handle it accordingly. But that is different issue
in your controller use it like this:
$ratings = Ratings::orderBy('rating','desc')->take(6)->get();

Join 2 tables to a Pivot table LARAVEL 4.2

How can i show the classes only for student who is enrolled in a class and i have 2 tables and a pivot table?
Table 1: Home_Students : home_id , home_studid ....
Table 2: Hw_Classes :class_id , class_desc , class_date ....
Pivot table:Hw_StudentClasses :Stclass_id, Stclass_classid, Stclass_studid
So i made a model MySeminarClasses to communicate with the table Hw_StudentClasses and a Controller MySeminarClassesController
I made relations in the model of the other tables belongsToMany
public function Users(){
return $this->belongsToMany('User','home_id');
}
public function SeminarClass(){
return $this->belongsToMany('SeminarClass','class_id');
}
Also in the Controller i did this which im not so sure if its right but i did this from the instructions of the laravel 4.2 documentation
$myclasses = DB::table('Hw_StudentClasses')
->join('Hw_Classes','Hw_StudentClasses.Stclass_classid','=','Hw_Classes.Class_id')
->join('Home_Students','Hw_StudentClasses.Stclass_studid','=','Home_Students.home_studid')
->orderBy('class_date',strtotime('-4 month'))
->get();
Finally in the blade
<tbody>
#foreach($myclasses as $i=>$myclass)
<tr>
<td>{{ $i+1 }}</td>
**<td>{{ link_to_route('class.show',$myclass->Class_desc,$myclass->Class_id) }}</td>**
<td class="text-center">{{ date('j-n-Y G:i',strtotime($myclass->class_date)) }}</td>
<td class="text-center">{{ UserEnroll::where('Stclass_classid',$myclass->Class_id)->count() }}</td>
</tr>
#endforeach
</tbody>
After a 16 hours of struggle ......i aswered my own question ! This query with Auth::user helped me. Show the classes only for every user who is logged in
$id = Auth::user()->home_studid;
$date = date('m-d-Y', strtotime('-4 month'));
$seminars = Seminar::where('Package_Display', 1)
->orWhere('Package_Display', 2)
->orderBy('Package_Name', 'asc')
->get();
$myclasses = DB::table('Hw_StudentClasses')
->join('Hw_Classes','Hw_StudentClasses.Stclass_classid','=','Hw_Classes.Class_id')
->join('Home_Students','Hw_StudentClasses.Stclass_studid','=','Home_Students.home_studid')
->where('Home_Students.home_studid','=',$id)
->orderBy('class_date',strtotime('-4 month'))
->get();
HOPE THIS HELPS SOMEONE ! ^_^

Resources