How to display a hasMany() relationship through a table in a view. - php

I'm trying to display a table in my view with contents that consists of information from my Location table (Addr, City, etc...) and Resource table (Name, Descr.), they're linked by ID's through a ResourceLocation Table. Here's what I have so far:
Resource Controller
....
public function resource()
{
$resources = Resource::all();
return view('pages.resource', compact('resources'));
}
public function location()
{
$locations = Location::all
return view (compact('locations'));
}
public function resourcelocation()
{
$resourcelocations = ResourceLocation::all();
return view (compact ('resourcelocations'));
}
...
ResourceLocation Model
/**
* Class ResourceLocation
*/
class ResourceLocation extends Model
{
...
public function resource ()
{
return $this->belongsTo('App\Models\Resource');
}
public function location ()
{
return $this->belongsTo('App\Models\Location');
}
}
Resource Model
/**
* Class Resource
*/
class Resource extends Model
{
...
/** A resource can have many locations */
public function location()
{
return $this->hasMany('App\Models\ResourceLocation');
}
}
Location Model
/**
* Class Location
*/
class Location extends Model
{
...
public function resource()
{
return $this->hasMany('App\ResourceLocation');
}
}
resource.blade.php
<table>
<tr>
<th>Resource Name</th>
<th>Description</th>
<th>Address</th>
<th>City</th>
<th>Zip Code</th>
<th>County</th>
</tr>
#foreach ($resourcelocations as $resourcelocation)
<tr>
<td> {{ $resourcelocation->id }}</td>
<td>
#foreach ($resourcelocation->resources as $resource)
{{ $resource->Name }},
#endforeach
</td>
<td>
#foreach($resourcelocations->locations as $location)
{{ $location->City }}
#endforeach
</td>
</tr>
#endforeach
</table>
I just wanted to add a column or two to see if it was working, but I keep getting an undefined variable on resourcelocations, still trying to wrap my head around laravel and how the relationships work, so maybe my logic is messed up. Any help would be great!
Thanks.

There seems to be some confusion in your relationships. I think it could work with the way you have it but you are making it much more confusing than it needs to be.
First, start with removing the ResourceLocation model. You can relate resources and locations directly without need of the intermediary model (you will still need that table though). This is what's called a belongs-to-many relationship.
I also recommend when you have a relationship which can return many records (for example if a resource can have many locations) you should name the method which relates these locations rather than location.
With all that in mind, your Resource model gets...
public function locations()
{
return $this->belongsToMany('App\Models\Location', 'ResourceLocation');
}
Where I put 'ResourceLocation', that should be whatever you named your pivot table.
Same for your Location model which receives.
public function resources()
{
return $this->belongsToMany('App\Models\Resource', 'ResourceLocation');
}
Now that should be greatly simplified, we just replaced 4 relationship methods and 3 models for 2 relationship methods and 2 models.
Now for your controller, it's much more efficient to use eager loading to grab all your resource locations.
$resources = Resource::with('locations')->get();
And in your view...
#foreach ($resources as $resource)
#foreach ($resource->locations as $location)
<tr>
<td>{{ $resource->id }}</td>
<td>{{ $location->name }}</td>
</tr>
#endforeach
#endforeach

In your Resource Controller you are not passing any resourcelocation variable as I can see only resources has been called. try declaring the variable in array in this line return view('pages.resource', compact('resources'));
To get the first element in hasMany you can try below:
$resource->location()->first();
you can use dd(variable_name) before sending the data to the view to get a better idea of how your data is managed

Related

Retrieving data based on One To Many Relationship

I have two tabled called categories and resources table.
Basically each resource has a category and the category id is saved on a column called resource_category_id in resources table.
So in order to setup One To Many relationship between the Models, I did these:
Category:
class Category extends Model
{
protected $table = "categories";
protected $guarded = [];
public function resources()
{
return $this->hasMany(Resource::class);
}
}
Resource:
class Resource extends Model
{
protected $table = "resources";
protected $guarded = [];
public function category()
{
return $this->belongsTo(Category::class, 'resource_category_id');
}
}
And now I want to show all categories and the resources and that have the same resource_category_id like this:
#php($menuCounter = 0)
#foreach($categories as $cat)
<tr>
<td style="text-align:center">{{ ++$menuCounter }}</td>
<td style="text-align:center">{{ $cat->category_name }}</td>
<td>
<ul>
#foreach($category->resources() as $resource)
<li>{{ $ress->resource_name }}</li>
#endforeach
</ul>
</td>
</tr>
#endforeach
But now the categories are all appearing but the resources does not be shown and also no error returns!
So what's going wrong here?
How can I show the resources according to resource_category_id via Eloquent relationships methods?
Instead of:
#foreach($category->resources() as $resource)
do
#foreach($category->resources as $resource)
The first one is loading the builder, the second one the collection.
You can also specify the foreign key for resources relationship in Category Model:
public function resources()
{
return $this->hasMany(Resource::class, 'resource_category_id');
}

I can't acces the MODEL field on my database relationship

I can't access my MODEL field in my database
This is the code that I execute:
#foreach($clients as client)
{{$client->dependents->fname}}
{{$client->dependents->mname}}
{{$client->dependents->lname}}
#endforeach
This code returns an error : Property [fname] does not exist on this collection instance.
When I do this code:
#foreach($clients as client)
{{$client->dependents}}
#endforeach
This code returns a successful array of data.
This is my Client Model:
class Client extends Model
{
protected $guarded = [];
public function dependents() {
return $this->hasMany(Dependent::class);
}
}
And this is my Dependent Model:
class Code extends Model
{
protected $guarded = [];
public function client()
{
return $this->hasOne(Client::class);
}
}
How can I retrieve each field using the eloquent model method?
In order to access the fields on dependents model, you need to make a foreach, because the client model hasMany dependents and when you try to access simply $client->dependents->fname doesn't know which one to access.
So, you need to do the following:
#foreach($clients as $client)
#foreach($client->dependents as $dependent)
{{$dependent->fname}}
{{$dependent->mname}}
{{$dependent->lname}}
#endforeach
#endforeach
It is HasMany relation AND It returns multiple departments so that fname is undefined. Because it has an object of departments, not the department and you are missing $ from #foreach($clients as client).
#foreach($clients as $client)
#foreach($clients->dependents as $department)
{{$dependent->fname}}
{{$dependent->mname}}
{{$dependent->lname}}
#endforeach
#endforeach
Try this, It will work for you. Enjoy!

Laravel 5.4 relationship beLongsToMany

Hi i need fix returning view. I made relation and its returning array. How i can change this and i am not sure i made good function to relationship. I just trying lerning it i saw many tutorials and i know in Laravel is so kind magic tips to returning.
My function must showing events what user was joining. I think i make it but its returning array and when i try do something like that
#foreach($zapisevents as $zapisevent)
<table class="table">
<th>{{$zapisevent->eventsave->name}}</th>
</table>
#endforeach
i got error:
Property [name] does not exist on this collection instance. (View: /home/mariusz/Pulpit/www/szpital/resources/views/profil/profil.blade.php)
but when i use <th>{{$zapisevent->eventsave}}</th> its returning array.
There is function for joining to event
public function index()
{
$userid = Auth::user();
$zapisevents = User::with('eventsave')->where('id',(Auth::user()->id))->get();
return view('profil.profil', ['userid' => $userid], ['zapisevents' => $zapisevents]);
}
Model User:
public function eventsave()
{
return $this->belongsToMany(HomeModel::class,'save_events','users_id','events_id')->withTimestamps();
}
Model HomeModel <<<
public function usersave()
{
return $this->belongsToMany(User::class,'save_events','events_id','users_id');
}
Its returning:
[{"id":5,"name":"asdasdsa","title":"Wydzial 1","start":"2017-04-04
03:00:00","end":"2017-04-04 07:59:00","created_at":"2017-04-01
18:50:40","updated_at":"2017-04-01
18:50:40","pivot":{"users_id":3,"events_id":5,"created_at":"2017-04-01
18:50:58","updated_at":"2017-04-01
18:50:58"}},{"id":7,"name":"kkkkkkkkkkkkkkkkkkkkkkkk","title":"Wydzial
4","start":"2017-04-01 00:00:00","end":"2017-04-01
23:59:59","created_at":"2017-04-01 19:54:24","updated_at":"2017-04-01
19:54:24","pivot":{"users_id":3,"events_id":7,"created_at":"2017-04-01
19:55:41","updated_at":"2017-04-01 19:55:41"}}]
the
#foreach($zapisevents as $zapisevent)
<table class="table">
<th>{{$zapisevent->eventsave->name}}</th>
</table>
#endforeach
Should ne
#foreach($zapisevents as $zapisevent)
<table class="table">
#foreach($zapisevent->eventsave as $eventSave)
<th>{{$eventsave->name}}</th>
#endForeach
</table>
#endforeach
in you code the name property is being called in a collection of HomeModel but it needs to be called in a model itself
When using arrays, you need to access their properties via their index like this:
$zapisevent->eventsave['name']
as opposed to:
$zapisevent->eventsave->name

Laravel cannot retrieve data using one to many not working

I have a problem with one to many relationship in Laravel. I cannot retrieve my data from database. My codes are following.
Doctor.php
public function cities()
{
return $this->belongsTo('App\City');
}
City.php
public function doctor()
{
return $this->hasMany('App\Doctor');
}
view
#foreach($doctors as $doctor)
<tr>
<td data-title="ID">{{ $doctor->id }}</td>
<td data-title="Name">{{ $doctor->name }}</td>
<td data-title="Hospital">{{ $doctor->hospital }}</td>
<td data-title="Designation">{{ $doctor->designation }}</td>
<td data-title="City">{{ $doctor->cities->name }}</td> <!-- problem in this line -->
</tr>
#endforeach
When I try to view the data an error has been shown:
ErrorException in 3d7f581c490d492093e6e73f8ebd29525504e56b.php line 46:
Trying to get property of non-object (View: D:\xampp\htdocs\tourisms\root\resources\views\doctors\index.blade.php)
On the belongsTo side of the relationship, when the foreign key name is not specified, it is built using the name of the relationship. In this case, since your relationship is named cities, Laravel will look for the field doctors.cities_id.
If your foreign key is not cities_id, then you need to either change the name of your relationship method, or specify the name of the foreign key:
public function cities() {
return $this->belongsTo('App\City', 'city_id');
}
// or, better:
public function city() {
return $this->belongsTo('App\City');
}
Also, as mentioned by #Christophvh, the naming of your relationships is a little off, but not programmatically incorrect. It makes more sense and is more readable when belongsTo/hasOne relationships are named singular, and belongsToMany/hasMany relationships are named plural.
You are trying to loop a Collection and not an array.
2 solutions:
1)
add ->get(); when you are calling your relationship in your controller
2)
use
#foreach($doctors->all() as $doctor)
instead of
#foreach($doctors as $doctor)
Also a quick tip:
Your naming is not really telling what you are doing. You should swap them around like below. 'A doctor belongs to a city' & 'A city has many doctors'
Doctor.php
public function city()
{
return $this->belongsTo('App\City');
}
City.php
public function doctors()
{
return $this->hasMany('App\Doctor');
}

Laravel 4 - Access to Table through Relational Models

Edit: typo
I have two Models: Project and Task. Both are relational to each other:
Project.php
class Project extends Eloquent {
public function tasks()
{
return $this->hasMany('Task');
}
Task.php
class Task extends Eloquent {
protected $guarded = [];
public function project()
{
return $this->belongsTo('Project');
}
Through my ProjectsController I pass the necessary Variables to my Projects View, like this:
ProjectsController:
public function index()
{
$projects = Project::with('tasks')->get();
return View::make('projects.index')
->with('projects', $projects);
}
And in my View I loop through every Project to show everything on a table:
Projects List
<table>
<tr>
<th>Id</th>
<th>Titel</th>
<th>Description</th>
<th>Tasks</th>
</tr>
#foreach($projects as $project)
<tr>
<td>{{$project->id}}</td>
<td>{{$project->title}}</td>
<td>{{$project->description}}</td>
<td>{{$project->task}}</td>
</tr>
#endforeach
</table>
As you can see, the last td-Tag, should access data from the tasks table.
I know that the above View does not work. But I want to know in general, how I would go about it, if I want to output the number of tasks, each project has.
Or anything else, that explains, how I can access different tables, through relational Models, in this particular situation.
since you defined the project model with $this->hasMany('Task'); and fetched models with their tasks, you can simply do
{{ $project->task()->count() }}
be sure to call the tasks as if it were a function, instead of a property.

Categories