I have MyRoom.php and TotalCity.php in my project in which each room is categorizes inside a city
so that I did this in MyRoom.php
public function location()
{
return $this->belongsTo(TotalCity::class, 'location_id')->withTrashed();
}
and I did this in TotalCity.php
public function location()
{
return $this->hasMany(MyRoom::class , 'total_city_id')->withTrashed();
}
I have passed id with routes and controller like this
home.blade.php
id)}}">{{ $row->name }}
web.php
Route::get('/city/{id}/rooms/','SiteController#room')->name('room');
SiteController.php
public function room($id) {
$room = TotalCity::find($id)->location;
return view('frontend.pages.rooms', compact('room'));
}
rooms.blade.php
#foreach($room as $row)
<div class="room">
<img src="{{ asset(env('UPLOAD_PATH').'/' . $row['photoi1']) }}"/>
</div>
#endforeach
But this is not showing any rooms in any city while i have stored cities and rooms which comes under particular city in my database.
In the relationship method, you should mention foreign key and owner key as well,
for example in MyRoom.php:
public function location()
{
return $this->belongsTo(TotalCity::class, 'location_id', 'total_city_primary_key')->withTrashed();
}
you can read laravel documentioation for more detail.
foreignKey in TotalCity model is wrong :
public function location(){
return $this->hasMany(MyRoom::class, 'location_id')->withTrashed();
}
I strongly recommend you to change your model's names to City and Room. If you dont want to, make sure in both models you're connecting them to the correct table, you can achieve that using the $table variable in both models, like this:
$table = 'your_table_name';
This will make sure the table is connected right.
Also, you should make a few changes:
In your TotalCity model do this:
public function rooms()
{
return $this->hasMany(MyRoom::class , 'total_city_id')->withTrashed();
}
In your MyRoom model do this:
public function city()
{
return $this->belongsTo(TotalCity::class)->withTrashed();
}
In your SiteController do this:
public function room($id) {
$rooms = TotalCity::find($id)->rooms;
return view('frontend.pages.rooms', compact('rooms'));
}
In your View
#foreach($rooms as $room)
<h2>{{$room->name}}</h2>
<div class="room">
<img src="{{ asset(env('UPLOAD_PATH').'/' . $room['photoi1']) }}"/>
</div>
#endforeach
Related
I have two tables in Laravel
jalans
jalan_images
In one id_jalan can be many images, My relations like this
Model Jalan
// Model Jalan
public function jalanImage()
{
// return $this->hasMany('App\JalanImage', 'id_jalan');
return $this->hasMany(JalanImage::class, 'id_jalan');
}
public function firstImage()
{
// return $this->hasOne('App\JalanImage', 'id_jalan');
return $this->hasOne(JalanImage::class, 'id_jalan');
}
Model JalanImage
// Model JalanImage
public function jalan()
{
// return $this->belongsTo('App\Jalan', 'id_jalan', 'id');
return $this->belongsTo(Jalan::class, 'id_jalan', 'id');
}
I want to display data like title, created_at, and the first image in each id_jalan, in my Controller for display data like this
JalanController
// JalanController
public function jalan()
{
$jalan = Jalan::with('firstImage')->orderBy('created_at', 'DESC')->get();
return view('jalan.all', ['jalan' => $jalan]);
// dd($jalan->toArray());
}
In my view, first image from each id_jalan not displayed, my view like this
Blade View
#foreach($jalan as $row)
<div class="post-item clearfix">
<table border="0">
<tr>
<td width="170px">
<a href="#">
<img src="{{ asset('uploads/jalan/' .$row->first_image) }}" alt="" class="img-fluid" width="150px"></td>
</a>
<td>
<h4>{{ $row->title }}</h4>
<i class="icofont-wall-clock"></i> <time>{{ date('d F Y', strtotime($row->created_at)) }}</time>
<p style="color: #F3591F">{{ $row->category }}</p>
</td>
</tr>
</table>
</div>
#endforeach
When I display it with dd($jalan->toArray()); in my controller, the first_image displayed.
How to fix it?
Thank you
You should follow Laravel's (especially Eloquent's) advices and best practices regarding naming convention. That means your gallery_images table should have gallery_id field instead what you have there. Believe or not, that way you'll skip lot of unforced errors and questions. I will leave you answer of how I would do it in your place:
// \App\Gallery::class
class Gallery extends Model
{
public function galleryImages()
{
return $this->hasMany(GalleryImage::class);
}
public function firstGalleryImage()
{
return $this->hasOne(GalleryImage::class);
}
}
// \App\GalleryImage::class
class GalleryImage extends Model
{
public function gallery()
{
return $this->belongsTo(Gallery::class);
}
}
Basically you can set as many as you need methods in model that returns specific relation. In Gallery::class here, you can see I have set one more relation that would return just first image of that gallery. In controller you'd call it with
public function someControllerMethod()
{
$gallery = Gallery::with(['firstGalleryImage'])->first();
// or
$galleries = Gallery::with(['firstGalleryImage'])->get();
}
Now returned object $gallery or collection of $galleries would carry only first image related. In your case (and if you don't want to change names of fields) you need to follow documentation of how to set another model's keys as method's arguments.
you can use Laravel's Eloquent ORM ( Eager Loading ),
here is an example of a single Image(image) and multiple images (media) relationship.
public function media()
{
return $this->hasMany(Media::class, 'foreign_key', 'local_key');
}
public function defaultMedia()
{
return $this->hasOne(Media::class, 'foreign_key', 'local_key');
public function image()
{
return $this->defaultMedia();
}
I have set up two models and made the relationship between them. I want to pass the attributes of the user as well as the user_detail.
I have used a similar code somewhere and it worked perfectly. But it is not working here.
//This is the function in "User.php" model.
public function user_detail(){
return $this->hasOne('App\Profile');
}
//This is the function in "Profile.php" model.
public function user(){
return $this->belongsTo('App\User');
}
//edit function in ProfileController
public function edit($id)
{
$user=User::find($id);
return view('profile.edit')->with('data',$user->user_detail);
}
When I click the edit button in the view, I expect the extract all the details from user table as well as from user_detail table.
I think you should edit your this code a little bit
public function edit($id)
{
$user=User::findOrFail($id);
return view('profile.edit')->with('data',$user);
}
And in your blade file (profile.edit), You can get all details from User and Profile Model.
{{ $data->id }}
{{ $data->user_detail->YOURPARAMETERS }}
The problem is with the relationship naming. Make it camelCase like,
//This is the function in "User.php" model.
public function userDetail(){
return $this->hasOne('App\Profile');
}
//edit function in ProfileController
public function edit($id)
{
$user=User::find($id);
return view('profile.edit')->with('data',$user->userDetail);
}
Reference: https://github.com/laravel/framework/issues/4307#issuecomment-42037712
try using where instead of find and then use with:
$user = User::where('id', $id)->with('user_detail')->first();
return view('profile.edit')->with('data', $user);
In your model:
public function user_detail(){
return $this->hasOne('App\Profile', 'student_no');
}
I asked question whose link is:
Link
Now my problem is that I want to show "CategoryName' of in food details.For that I add function in Categories.php model as:
public function food()
{
return $this->hasMany('App\Food','food_categories','Category_id','Food_id');
}
and in food.php
public function restaurant()
{
return $this->belongsToMany('App\Restaurant','food_restaurant','Food_id','Res_id');
}
public function categories()
{
return $this->belongsTo('App\Categories','food_categories');
}
Then in show.blade.php I add:
#foreach ($food->restaurant as $restaurant)
<h3><p>RestaurantName:</h3><h4>{{$restaurant->ResName}}</p></h4>
<h3><p>Contact #:</h3><h4>{{$restaurant->Contact}}</p></h4>
<h3><p>Location:</h3><h4>{{$restaurant->Address_Loc}}</p></h4>
#endforeach
#foreach ($food->categories as $categories)
<h3><p>CategoryName:</h3><h4>{{$categories->CategoryName}}</p></h4>
#endforeach
And I changed controller to :
public function show($Food_id)
{
$food = Food::with('restaurant.categories')->findOrFail($Food_id);
return view('show', compact('food'));
}
But it does not shows me categoryname.Plz help me where is the problem?
With Eager loading, "dot" notation loads nested relations.
In your controller you do
Food::with('restaurant.categories')
..this queries the restaurant() relation on the Food model, and that Restaurant's categories() relation.
I think you might need to call
Food::with('restaurant', 'categories')
as this will query both relations on the Food model.
I have the following relationship between my tables
In my Models i have the following code:
Location Model:
public function member() {
return $this->belongsTo('App\Member','member_id');
}
Member Model:
public function locations(){
return $this->hasMany('App\Location','member_id');
}
Now in my Location controller I created the following function.
public function getFinalData(){
$locations = Location::with('member')->whereNotNull('member_id')->get();
return view('locations.final-list',['locations'=>$locations]);
}
In my blade template however, I am unable to iterate through the member properties
<ul>
#foreach($locations as $location)
<li>{{$location->id}}</li>
<li>
#foreach($location->member as $member)
{{$member->id}}
#endforeach
</li>
#endforeach
</ul>
This gives me the following error:
Trying to get property of non-object (View:locations/final-list.blade.php)
update: The result i'm trying to achieve corresponds to this query
SELECT locations.location_id,locations.name,members.first_name, members.last_name , locations.meters
FROM locations,members
WHERE locations.member_id = members.id
Update 2:
So i tried to access a single location with a single attached to it and that works perfectly
public function getFinalData(){
//$locations = Location::with('member')->whereNotNull('member_id')->get();
$location = Location::find(0);
return view('locations.final-list',['location'=>$location]);
}
in final-list
$location->member->first_name
**Update 3 **
Tinker Output for one record :
In your Location model, rewrite below function:-
public function member()
{
return $this->belongsTo('App\Member', 'id');
}
Get all locations with member detail as below:-
$locations = Location::with('member')->get();
Hope it will work for you :-)
For showing related tables information in blade is as shown:
Model Relations
Location Model:
public function member() {
return $this->belongsTo('App\Member','member_id');
}
Member Model:
public function locations(){
return $this->hasMany('App\Location','member_id');
}
Get all locations in your controller
$locations = Location::all();
return view('locations.final-list', compact('locations'));
Or
$locations = Location::orderBy('id')->get();
return view('locations.final-list', compact('locations'));
Inside your view(blade) write the following code:
<div>
#if($locations)
#foreach($locations AS $location)
<div>{{ $location->id }}</div>
#if($location->member)
#foreach($location->member AS $member)
<div>
{{ $member->id }}
</div>
#endforeach
#endif
#endforeach
#endif
</div>
hi i am using a custom repository and I am getting comfortable with querying one table to retrieve data like so:
public function getAll()
{
// get all logged in users projects order by project name asc and paginate 9 per page
return \Auth::user()->projects()->orderBy('project_name', 'ASC')->paginate(9);
}
and in my controller I simply call
public function __construct(ProjectRepositoryInterface $project) {
$this->project = $project;
}
public function index()
{
$projects = $this->project->getAll();
echo View::make('projects.index', compact('projects'));
}
and my view is as so:
#if (Auth::check())
#if (count($projects) > 0)
#foreach ($projects as $project)
{{ $project->project_name }}
#endforeach
#else
<p>No records, would you like to create some...</p>
#endif
{{ $projects->links; }}
#endif
However within my projects table I have a status_id and a client_id and I want to retrieve records of this these tables with the logged in user but I am not sure how to structure my query, does anyone have any guidance?
According to the laravel documentation, In your project model you can add the following function:
class Project extends Eloquent
{
public function clients()
{
return $this->hasMany(Client::class);
}
}
In your client model you can then add the inverse of the relationship with the function:
class Client extends Eloquent
{
public function project()
{
return $this->belongsTo(Project::class);
}
}
Then you can retrieve the data with a function like:
$clients = Project::find(1)->clients;