Laravel: How to paginate eloquent “hasMany” relationship from Model class? - php

class Product extends Model
{
public function prices() {
return $this->hasMany('App\Price', 'product_id')->orderBy('purchase_date', 'desc');
}
}
I want to use this in my blade - {{ $product->prices->render() }}

in your controller $prices = $product->prices()->paginate(); and just return it to view or api

First, you have to create a relationship between Product and Price
public function prices()
{
return $this->hasMany('App\Price', 'product_id');
}
Now, in your Product Controller, you can query like
Product::with('prices')->orderBy('created_at', 'desc')->paginate(10);
and now you can use it in your blade view with pagination, hope this answers your question

Related

How to filter entries via hasMany relationship in Laravel

I'm trying write an website with Laravel (current version is 5.7) and I have 3 models as: Post, User and Fav. I'm using a simple form to add posts to "favs" table which has 3 columns as; id, user_id and post_id. And I want to list posts that user added favorites bu I can't use "hasMany" method properly.
I can use variables like; $post->user->name but I can't figure it out how to use relationship with "favs" table.
Post Model
public function user() {
return $this->belongsTo('App\User');
}
public function favs() {
return $this->hasMany('App\Fav');
}
Fav Model
public function users() {
return $this->hasMany('App\User');
}
public function posts() {
return $this->hasMany('App\Post', 'post_id', 'id');
}
User Model
public function posts() {
return $this->hasMany('App\Post');
}
public function favs() {
return $this->hasMany('App\Fav');
}
Controller
public function user($id){
$favs = Fav::orderBy('post_id', 'desc')->get();
$user = User::find($id);
$posts = Post::orderBy('id', 'desc')->where('user_id', $id)->where('status', '4')->paginate(10);
return view('front.user')->with('user', $user)->with('posts', $posts)->with('favs', $favs);
}
The Fav model only has one User and Post each, so you need to use belongsTo() instead of hasMany and change the method names to singular. You can also remove the additional parameters in post() since they're the default values.
public function user() {
return $this->belongsTo('App\User');
}
public function post() {
return $this->belongsTo('App\Post');
}
Loading all Posts that a user has favorited:
$user->favs()->with('post')->get();
The with() method is used to eager load the relationship.
Now you can loop through the Favs:
#foreach($favs as $fav)
{{ $fav->post->name }}
#endforeach
I think you can change these two lines of your code to
$posts = Post::orderBy('id', 'desc')->where('user_id', $id)->where('status', '4')->paginate(10);
return view('front.user')->with('user', $user)->with('posts', $posts)->with('favs', $favs);
to
$posts = Post::where('user_id', $id)->where('status', '4')->latest()->paginate(10);
return view('front.user', compact('user', 'posts', 'favs'));
And for retrieving favorite posts of an user,
if you will change the fav table to make it a pivot table only to handle a many to many relationships between Post and User, you can get it as $user->posts, for a separate model, I think you can consider something like $user->favs and in view
In Fav model
public function user() {
return $this->belongsTo('App\User');
}
public function post() {
return $this->belongsTo('App\Post');
}
and in view
#foreach ( $user->favs as $fav )
{{ $fav->post->id }}
#endforeach
If an User, per example, have many Favs you need to use a Iteration Block, like foreach.
Example:
foreach($user->favs as $fav) {
dd($fav) // do something
}
Ps.: Be careful not to confuse hasMany and belongsToMany.

Retrieving eloquent relationship with laravel

When I try to get the name of the Category from my product, I discovered I had to use a 'C' rather than a 'c' before it retrieved results. However when I try to get the Supplier name, the lowercase s works just fine. I was wondering what is causing this difference. Also if I dd($var), is the relations field expected to be empty. I assumed it would have something related to the relationships defined in my models.
Blade.php
<td>{{$product->Category->name}}</td>
<td>{{$product->salePrice}}</td>
<td>{{$product->stock}}</td>
<td>{{$product->supplier->company_name}}</td>
Product.php
public function category()
{
return $this->belongsTo('App\Category','category');
}
public function supplier()
{
return $this->belongsTo('App\Supplier','supplier_id');
}
Category.php
public function product()
{
return $this->hasMany('App\Product');
}
Supplier.php
public function product()
{
return $this->hasMany('App\Product');
}
You're missing a _id on your Product model:
public function category()
{
return $this->belongsTo('App\Category','category_id');
}
Or leave empty
public function category()
{
return $this->belongsTo('App\Category');
}
In your Controller
public function index()
{
$products = Product::all()->with('category');
return view('your_view', compact('products'));
}
If you dd the products
In your View you will se that the relation has been loaded because of the
Eager Loading
When accessing Eloquent relationships as properties, the relationship data is "lazy loaded". This means the relationship data is not actually loaded until you first access the property. However, Eloquent can "eager load" relationships at the time you query the parent model.
#foreach($products as $product)
<td>{{$product->category->name}}</td>
<td>{{$product->salePrice}}</td>
<td>{{$product->stock}}</td>
<td>{{$product->supplier->company_name}}</td>
#endforeach

How to create a relationship between User and Posts in Laravel

I have a blog and want to include the Users Name when shown to the public.
When creating the blog I make sure to include the user_id in the blogs table
In my Blog model I have the following:
public function users()
{
return $this->belongsTo(User::class);
}
In my Users model I have:
public function blogs()
{
return $this->hasMany(Blog::class);
}
In my Blog Controller I have:
public function index(User $user)
{
$users = User::get();
$blogs= DB::table('blogs')->where('user_id', '=', $users->id)->orderBy('id', 'DESC')->paginate(6);
return view('blogs.index',compact('blogs'));
}
Then in my view:
#foreach($blogs as $blog)
<h1>{{$blog->title}}</h1>
Source:{{$blog->users->first_name}} // This does not work
Source:{{$blog->first_name}} // This does not work either
#endforeach
I thought I could do something like this to show the names:
{{ $blogs->users->first_name }} {{ $blogs->users->last_name }}
But this isn't working either...
Try this:
#foreach($blogs as $blog)
<h1>{{$blog->title}}</h1>
{{$blog->user->first_name}}
#endforeach
And on your Blog Model
public function user()
{
return $this->belongsTo(User::class);
}
In your Blog controller the variable $blog needs to be $blogs. You also have extra characters (right parenthesis) in your Blade. It should be:
#foreach($blogs as $blog)
Source: {{ $blog->user->first_name }}
...
#endforeach
Blog Model
This function replaces the old "users" function, as only one user is returned (belongsTo is a singular relationship).
class Blog extends Model
{
public function user()
{
return $this->belongsTo('App\User');
}
}
User Model
public function blogs()
{
return $this->hasMany('App\Blog');
}
Controller Function
And, as such, you can cut down your controller code, including removing the redundant elements.
public function index(User $user)
{
$blogs = Blog::where('user_id', '=', $user->id)->orderBy('created_at','desc')->paginate(6);
return view('blogs.index', compact('blogs'));
}
The way you did is called Query Builder
$blogs= DB::table('blogs')->where('user_id', '=', $users->id)->orderBy('id', 'DESC')->paginate(6);
Query Builder does not support lazy loading, cause lazy loading is only supported for the Eloquent method
$blog->users->first_name
For Eloquent way you can try this instead:
$blogs = Blog::where('user_id', $user->id)->get()
foreach($blogs as $blog){
dd($blog->user); // you will get the user detail here
}
For lazy loading have a performance issue when come to load heavy data so to prevent lazy loading can use this
$blogs = Blog::with('user')->where('user_id', $user->id)->get()
For more information can look at Eloquent Relationship Documentation
For query builder, the only way to link your user is use join, which will be something like this
$blogs = DB::table('blogs')
->join('users', 'users.id', '=', 'blogs.user_id')
->get();
foreach($blogs as $blog){
dd($blog->first_name) // user first name
}
For more information can look at Query Builder Join
BlogController.php
public function index(){
$blogs = Blog::with('user')->get();
return view('blogs.index')->with('blogs',$blogs);
}
Blog.php
public function user()
{
return $this->belongsTo('App\User');
}
User.php
public function blogs()
{
return $this->hasMany('App\Blog');
}

Show data from multiple tables in view laravel

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.

Eloquent ORM multiple relationships

There are three tables.
users:
- ...
- some_param
admins:
- ...
- club_id
- some_param
clubs:
- id
- title
Each user can have multiple admins (related by some_param), each admin can have multiple clubs, and I want to get each club's title.
So I defined a relations:
class User extends Eloquent {
public function admins() {
return $this->hasMany('Admin', 'some_param', 'some_param');
}
}
class Admin extends Eloquent {
public function clubs() {
$this->hasMany('Club', 'id', 'club_id');
}
}
And want to use it in template:
#foreach($user->admins as $admin)
#foreach($admin->clubs as $club)
{{ $club->title }}
#endforeach
#endforeach
But I'm getting an error: Relationship method must return an object of type Illuminate\Database\Eloquent\Relations\Relation at line #foreach($admin->clubs as $club).
What's I am doing wrong? Thank you in advance.
In your following function:
public function clubs() {
$this->hasMany('Club', 'id', 'club_id');
}
You didn't return so use return like this:
public function clubs() {
return $this->hasMany('Club', 'id', 'club_id');
}
Also, when getting User collection in $user variable, try to use eager loading, for example:
$user = User::with('admins.clubs')->find(1);
This will reduce the queries.

Categories