Showing related table information in blade template laravel - php

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>

Related

Showing Empty after using eloquent un laravel

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

PHP Laravel orderby not working if using `count`

I want to sort/order my data by its release_date but I get an error I don't understand:
In my Controller I have:
public function index() {
$releases = Release::orderBy('release_date', 'desc');
return view('pages.index')->with('releases', $releases);
}
and in my view file I have this:
#if (count($releases) > 0)
#foreach ($releases as $release)
<div>
<p>{{$release->artist}} - {{$release->album_title}} <span>ReleaseDate: {{$release->release_date}}</span></p>
</div>
#endforeach
#endif
This returns the error:
count(): Parameter must be an array or an object that implements
Countable
What does this mean? Can someone help me out?
Try this code:
public function index()
{
$releases = Release::orderBy('release_date', 'desc')->get();
return view('pages.index')->with('releases', $releases);
}
The reason you code wasn't working before is because orderBy won't perform the query, it will simply add to it. In this case you need to chain on get() at the end in order to perform the query and get the results otherwise you will just get an instance of the query builder.
Change Controller
public function index() {
$releases = Release::orderBy('release_date', 'desc')->get();
return view('pages.index',compact('releases');
}
change View
#if ($releases->count() > 0)
#foreach ($releases as $release)
<div>
<p>{{$release->artist}} - {{$release->album_title}} <span>ReleaseDate: {{$release->release_date}}</span></p>
</div>
#endforeach
#endif

Laravel multiple controller functions one route

What I'm trying to achieve is post all news by #foreach and between the #foreach do another #foreach to post all comments with the ID from the news post.
I'm unsure on how to pass this ID, to the getNewsComments function.
My controller:
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use DB;
use App\News;
use App\newsComments;
class newsController extends Controller
{
public function getAllNews(){
$results = News::all();
return view('index')->with('news', $results);
}
}
Route:
Route::get('/', 'newsController#getAllNews');
News model:
class News extends Model
{
// set table
protected $table = 'lg_news';
public function newsComments(){
return $this->hasMany('App\newsCommments');
}
}
Comment model:
class newsComments extends Model
{
// set table name
protected $table = 'lg_newscomments';
}
view
#foreach ($news as $article)
#foreach($news->$newsComments as $comment)
#endforeach
#endforeach
Error:
Undefined variable: newsComments (View:
C:\xampp\htdocs\resources\views\index.blade.php)
Change this line:
return view('index')->with('news', $results);
to
return view('index', ['news' => $results]);
and it probably will work.
PS: with() function will set a session! It will not pass a variable to view.
You don't need multiple routes you just need to have two tables related to each other with 1:N relationship
Article (1) -> Comments (N)
Then you will create a model for each table and create the relation like explained in the Laravel documentation
One to Many relationship in Laravel
Then you will fetch all posts and pass them to the view:
public function getAllArticles()
{
$posts = Post::all();
return view('view-name', $posts);
}
And at the end, create a view and show posts and comments:
#foreach($posts as $post)
{{ $post->title }}
{{ $post->body }}
#foreach($post->comments as $comment)
{{ $comment->title }}
{{ $comment->body }}
#endforeach
#endforeach
Reminder: $post->comments , comments is the method name defined in the model where you create the relationship
Define route at web.php:
Route::get('/', 'ControllerName#getAllArticles');
Go to localhost:8000/ (or to your site domain if the site is hosted) to see the result

laravel eloquent repository query foreign key tables

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;

Trouble retrieving data laravel4(oneToMany)

Okay so I just started learning Laravel and its fantastic. I just got stuck trying to retrive all the post from a user. Here is my code
models/User.php
public function posts()
{
$this->hasMany('Post');
}
models/Post.php
public function user()
{
$this->belongsTo('User');
}
controller/UserController.php
public function getUserProfile($username)
{
$user = User::where('username', '=', $username)->first();
$this->layout->content = View::make('user.index', array('user'=>$user));
}
views/user/index.blade.php
<div class="show-post">
<ul>
<li>{{ $user->posts }}</lo>
</ul>
</div>
I also tried:
#foreach($user->posts as $post)
<li>{{$post->post}}</li>
#endforeach
So im having trouble displaying the post for each specific user. Thank you.
So with the help of #WereWolf- The Alpha I was able to solve it and make my code better, If you notice I forgot to return my relationship functions. example:
Notice I hadn't returned it before
models/Post.php
public function users()
{
return $this->belongsTo('users');
}
But also the way I was querying my database was inefficient so Alpha showed me Eager Loading
http://laravel.com/docs/eloquent#eager-loading
example of controller
public function getUserProfile($username)
{
$user = User::with('posts')->where('username', '=', $username)->first();
$this->layout->content = View::make('user.index', array('user'=>$user));
}
and finally the view:
div class="show-post">
#foreach($user->posts as $post)
{{ $post->post }}
#endforeach
</div>
Actually $user->posts returns a collection of Post model so when you try this
{{ $user->posts }}
Laravel tries to echo that collection object which is not possible. You may try foreach loop instead:
#foreach($user->posts as $post)
{{ $post->somepropertyname }}
#endforeach
It's also possible to do something like this:
// Get first post->somepropertyname
{{ $user->posts->first()->somepropertyname }}
// Get last post->somepropertyname
{{ $user->posts->last()->somepropertyname }}
// Get first post->somepropertyname (same as first)
{{ $user->posts->get(0)->somepropertyname }}
// Get second post->somepropertyname from collection
{{ $user->posts->get(1)->somepropertyname }}
// Get the post->somepropertyname by id (post id) 2
{{ $user->posts->find(2)->somepropertyname }}
Also you may use eager loading like this (better):
$user = User::with('posts')->where('username', '=', $username)->first();
You may like this article about Cocllection.
Update: Also use return in model methods, like:
public function posts()
{
return $this->hasMany('Post');
}

Categories