I'm using Laravel 5.6 and I have created two Models Question and User Model and these are linked to each other using one to many relation as:
Question Model
public function user() {
return $this->belongsTo('App\User');
}
User Model
public function questions() {
return $this->hasMany('App\Question');
}
And my controller code is:
public function index()
{
$user = User::all();
return view('home', compact('user'));
}
So, i'm trying to get question title and I have written this code in blade:
#foreach($user as $user)
{{ dd($user->questions->questions_title) }}
#endforeach
But getting error undefined index questions_title, but if only write this {{ dd($user->questions) }} it gave me all questions, so how to fix it.
I have also tried {{ dd($user->questions['questions_title']) }} but not fixed.
You'll want to loop over your questions relationship to see your question:
#foreach($user as $u)
#foreach($u->questions as $question)
{{ dd($question->questions_title) }}
#endforeach
#endforeach
Note: I changed $user to $u
In your controller, you are not eager loading your questions relationships. Change your code to the following:
public function index()
{
$user = User::with('questions')->get();
return view('home', compact('user'));
}
Using the with() method will load all specified relationship with the eloquent query. After this, you will need to loop through the questions collection using the ->each() collection method.
#foreach($users as $user)
#foreach($user->question as $question)
{{ $question->question_title }}
#endforeach
#endforeach
No need for two foreach loops we can simply use one like below:
#foreach ($user->questions as $question)
{{ dd($question->questions_title) }}
#endforeach
Related
I'm the beginner of laravel 6. I just want to ask. I want to display data but it doesn't show.
index.blade.php:
#if(isset($teachers))
#foreach($teachers->qualifs as $qualif)
<li>{{ $qualif->qual }}</li>
#endforeach
#endif
Controller:
public function index()
{
$teachers= DB::table('teachers')->first();
$qualifs = DB::table('qualifs')->find($teachers->id);
return view('teachers.index',compact('teachers','qualifs'));
}
qualif.php:
public function teachers()
{
return $this->belongsToMany('todolist\teacher', 'qualif_teachers');
}
teacher.php:
public function qualifs()
{
return $this->belongsToMany('todolist\qualif', 'qualif_teachers');
}
Note: Data is storing correctly, only displaying issue.
ERROR:Undefined property: stdClass::$qualifs
relationship belongs to a model instance that means to an eloquent object. when you are using query builder you will get stdObject instead of an eloquent object. and thus your relationship is not working. to make this work you have to use eloquent instead of query builder.
public function index()
{
$teachers= teacher::get();
return view('teachers.index',compact('teachers'));
}
and view will be like
#foreach($teachers as $teacher)
#foreach($teacher->qualifs as $qualif)
<li>{{ $qualif->qual }}</li>
#endforeach
#endforeach
What is the most effective way for returning data from two tables in on view?
Like an employee check the vehicle for each order.
Route::get('orderVehicle',"adminController#orderVehicle");
public function orderVehicle(Request $reques){
$orders = new Order;
$vehicles = new Vehicle; $orders->id; $vehicles->id; return view('adminVeiw.orderVehicle',compact('orders','vehicles')); }
#foreach($orders as $or) {{ $or->id }} #endforeach {{ $vehicles->id }}
And the error is
"Trying to get property 'id' of non-object (View:
/var/www/html/full-Restaurant-App-Using-Laravel/resources/views/adminVeiw/orderVehicle.blade.php)"
So any suggestions?
do this if you don't wanna change your code in controller
#foreach($orders as $or)
#if(!empty($or->id))
{{ $or->id }}
#endif
#endforeach
#if(!empty($vahicles->id))
{{ $vehicles->id }}
#endif
in this case you won't get error but i don't know how you wanna this works for you,
i hope it helps
public function orderVehicle()
{
$orders = Order::create();
$vehicles = Vehicle::create();
return view('adminVeiw.orderVehicle', compact('orders', 'vehicles'));
}
Just an example:
let's say I have Post model, and the Comment model. Post, of course, have Comments, one-to-many relation.
I have to display list of posts with comments below it.
I'll get my posts in the controller:
$posts = Post::get(), I'll pass it to the blade view and then I'll loop through it
#foreach($posts as $post)
{{ $post->title }}
{{ $post->comments }}
#endforeach
where $post->comments is some relation
public function comments()
{
return $this->hasMany(Comment::class);
}
As we know, that query will be executed many times.
Now my question: how we should optimize it?
Return Cache::remember in the getter?
Get (somehow?) those comments, when getting the posts in one query? Something like join query? I know that I can write that kind of query, but I'm talking about Eloquent's query builder. And then how get the comments within the loop? Wouldn't {{ $post->comments }} call the relation again instead of getting stored data?
Different solution?
You can do $posts = Post::with('comments')->get() to eager load the comments with the post. Read more about it in the documentation: https://laravel.com/docs/5.7/eloquent-relationships#eager-loading
Also, to display the comments you would want to add another foreach loop. It would look something like this:
#foreach($posts as $post)
{{ $post->title }}
#foreach($post->comments as $comment)
{{ $comment->title }}
#endforeach
#endforeach
You’ve probably cached some model data in the controller before, but I am going to show you a Laravel model caching technique that’s a little more granular using Active Record models
Note that we could also use the Cache::rememberForever() method and rely on our caching mechanism’s garbage collection to remove stale keys. I’ve set a timer so that the cache will be hit most of the time, with a fresh cache every fifteen minutes.
The cacheKey() method needs to make the model unique, and invalidate the cache when the model is updated. Here’s my cacheKey implementation:
public function cacheKey()
{
return sprintf(
"%s/%s-%s",
$this->getTable(),
$this->getKey(),
$this->updated_at->timestamp
);
}
public function comments()
{
return $this->hasMany(Comment::class);
}
public function getCachedCommentsCountAttribute()
{
return Cache::remember($this->cacheKey() . ':comments_count', 15, function () {
return $this->comments->count();
});
}
yes u can do like that in controller
$minutes = 60;
$posts = Cache::remember('posts', $minutes, function () {
return Post::with('comments')->get()
});
in blade u can get like that
#foreach($posts as $post)
{{ $post->title }}
#foreach($post->comments as $comment)
{{ $comment->title }}
#endforeach
#endforeach
for more information read this article
I'm trying to get all the users where a given method in User model meets. Please see my code below:
User.php
public function isPicker(){
return ($this->where('isPicker', 1)) ? true : false;
}
Now, I can use User::all();, but it returns all the users. What I want is to only return the users that meets the isPicker() method. What I'm trying to do in view is:
#foreach($users as $user)
#if($user->isPicker())
{{ $user->first_name }}
#endif
#endforeach
This is also working fine, but it is not that efficient to use. What if there's a lot of method to check? Any idea for this?
Just do:
$users = User::where('isPicker', 1)->get();
Or create a scope:
public function scopeIsPicker($query)
{
return $query->where('isPicker', 1);
}
// usage
$users = User::isPicker()->get();
Well you could change you code up a little to look like this.
#foreach($users->where('isPicker', 1)->all() as $user)
{{ $user->first_name }}
#endforeach
But this will only work if the users var is a collection.
Other wise just change you query on how your getting the users to something like this.
User::where('isPicker', 1)->get()
Instead of checking in model file, you can directly query in your controller try below code
if you want to display only isPicker=1 users.
Controller Code :
$users = User::where('isPicker', 1)->get();
Blade code :
#foreach($users as $user)
{{ $user->first_name }}
#endforeach
OR
if you want to display all users including isPicker 0&1.
Controller Code :
$users = User::all();
Blade code :
#foreach($users as $user)
#if($user->isPicker == 1)
{{ $user->first_name }}
#else
<p>Picker is 0</p>
#endif
#endforeach
Note : Remove your isPicker function from user model file because its unuse.
I'm trying to get the total comments the user have..
Controller:
public function index()
{
$setting = Setting::findOrFail(1);
$comments = Comment::where('published', '=', '1')->get();
$users = User::all();
return view('page.index', compact('setting', 'comments', 'users'));
}
View:
#foreach($comments as $comment)
{{ count($users->where('user_id', '=', $comment->user_id)) }}
#endforeach
The problem is that it only returns 0 and i have 2 comments there.. even using the user id to instead of "$comment->user_id" it doesnt work. still display 0.
$users is a collection, not a query. Treat it as such:
#foreach ($comments as $comment)
{{ $users->where('user_id', $comment->user_id)->count() }}
#endforeach
The collection's where method does not take an operator.
From the wording in your question it seems you actually want it the other way around:
$comments = Comment::wherePublished(1)->get()->groupBy('user_id');
Then in your view:
#foreach ($users as $user)
{{ $comments->has($user->id) ? count($comments[$user->id]) : 0 }}
#endforeach
I'm late to answer your question and Joseph already showed you the problem but you may also do it differently. You can group comments using Collection::groupBy, for example:
$comments = Comment::all()->groupBy('user_id');
Then in your view you may try this:
#foreach($comments as $user => $userComments)
// count($userComments)
// Or
#foreach($userComments as $comment)
// {{ $comment->title }}
#endforeach
#endforeach
In the first loop (#foreach($comments as $user => $userComments)), the $user is the user_id and it's value would be all comments (an array) by this user but in group.