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

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();

Related

Sort the data linked by a relationship by date

I'm having a problem sorting projects based on the date of the last task associated with it. I explain better.
I have a relationship between project and tasks One to Many (as a project can have one or more tasks). In the project table, for each project, I have a column where I print the date of the last task done, as you can see in the blade view shown below. So far everything ok.
Now the projects are sorted by default in ascending order of creation of each project (so the last project shown in the table is the one that is added last).
What I want is to sort the projects by the date obtained from the last task associated with that project through the column corresponding to the date of the last task I get as shown below.
Model Project:
class Project extends Model
{
use HasFactory;
protected $fillable = [
'title',
'name',
];
public function tasks()
{
return $this->hasMany(Task::class);
}
}
Controller:
public function index()
{
$projects = Project::withCount('tasks')->get();
return view('project.index', compact('projects'));
}
View:
<table id="tabledata">
<thead>
<tr>
<th></th>
<th>Title</th>
<th>Name</th>
<th>Date last task</th>
<th>N. Tasks</th>
</tr>
</thead>
<tbody>
#foreach ($projects as $project)
<tr>
<td></td>
<td class="p-4">{{ $project->title}}</a></td>
<td class="p-4">{{ $project->name }}</a></td>
<td class="p-4">{{ $project->tasks()->latest()->first()->created_at->format('d/m/Y') }}</td>
<td class="text-center">{{ $project->tasks_count}}</td>
</tr>
#endforeach
</tbody>
</table>
To sort your query by the data of relationship column, you can change your query to something like this:
$projects = Project::with('tasks')->orderByDesc(Task::select('created_at')->whereColumn('tasks.project_id', 'project.id')->latest()->take(1))->withCount('tasks')->get();
orderBy() and orderByDesc() query builder methods support passing a query, instead of just a column name.
What we did here is:
We took the tasks of the project
We passed in a query as a subquery to the orderByDesc query builder method.
Inside the subquery:
We selected the created_at column from the tasks table.
We limited the results by comparing the project_id column of tasks table to the id column of the projects table.
Then we call the latest() method, which sorts the tasks to the recent record first.
And lastly, we limit the results to only one row, since a subquery can only return a single row and column
You can read more about how it works with different types of relationships here

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

show all data from parent and child table

I have two simple one to many relationship tables of medicines and bills. as it happens, many medicines are bought by a single bill.
Now I have a page to show all the bills in each row of a table. Also, I want to be able to view all the sold medicines related to each bill by clicking on the respective bill and the medicines will show up below the row using JQuery.
This is my view code to depict all the bills in a table:
<tbody>
#foreach($bills as $bill)
<tr role="row" class="odd">
<td class="v-align-middle semi-bold">{{$bill->id}}</td>
<td class="v-align-middle semi-bold">{{$bill->customername}}</td>
<td class="v-align-middle">{{$bill->paid}}</td>
<td class="v-align-middle">{{$bill->remainders}}</td>
<td class="v-align-middle">{{$bill->total}}</td>
<td class="v-align-middle">{{$bill->created_at}}</td>
</tr>
#endforeach
</tbody>
and my controller code is:
public function index()
{
$bill = Billpc::all();
return view('bills')->with('bills', $bill);
}
Can anyone help me with how to show all the sold medicines related to the respective bill?
add relationships in your model
Bill model
public function medicines()
{
return $this->hasMany('App\Submission');
}
Medicine model:
public function bill()
{
return $this->belongsTo('App\AssignSubmission');
}
then change your code in your controller. use with to get the medicines in your bill
Controller
public function index()
{
$bill = Billpc::with('medicines')->get();
return view('bills')->with('bills', $bill);
}

How i get the name of user in this foreach

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.

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