Laravel relationship pagination - php

I am trying to paginate the products please refer to the following code:
Here is my show.blade.php
#foreach ($category->products as $product)
<h2>{{ $product->name }}</h2>
#endforeach
Here is my CategoriesController.php
public function show($slug)
{
$category = Category::where('slug', $slug)->firstOrFail();
return view('category.show', compact('category'));
}

You need to paginate the products in the controller method and then pass the paginated result to the view.
public function show($slug)
{
$category = Category::with('products')->where('slug', $slug)->firstOrFail();
$products = $category->products()->paginate(10);
return view('category.show', compact('products'));
}
Then in blade view
#foreach($products as $product)
<h2>{{ $product->name }}</h2>
#endforeach
//To show the pagination links
{!! $products->links() !!}

Related

Database data is not an array or object

I want to print '$post' as an array from database.
<tbody>
#if (is_array($posts) || is_object($posts)){
#foreach ($posts as $post)
<tr>
<th>{{$post->id }}</th>
<td>{{$post->title }}</td>
<td>{{$post->body }}</td>
<td>{{$post->created_at }}</td>
<td>ViewEdit</td>
</tr>
#endforeach
#else
{{'no!'}}
#endif
</tbody>
it just prints no! this is the main function:
public function index()
{
$posts = Post::all();
return view('posts.index')->withPosts('$posts');
}
You should below way to pass the data from view file.
public function index()
{
$posts = Post::all();
return view('posts.index',compact('posts'));
}
You can use get method , get will return all of the results in the model's table. After that you can pass the result to your view.
public function index(){
$posts = Post::get();
return view('posts.index',compact('posts'));
}

Get all the data with specific tag in laravel

I am using eloquent relationships for post and tags through post_tags. What i'm trying to do is make sections of posts in my front-end view with specific tags. Like if i have a section 1 it should have all posts of tag "new", section 2 should have all posts of tag "old" etc. And i want all of this to happen in a same view.
Post Model
public function tags()
{
return $this->belongsToMany('App\Tag', 'post_tag');
}
Tag Model
public function posts()
{
return $this->belongsToMany('App\Post', 'post_tag');
}
Controller
public function index()
{
$posts = Post::all();
return view('frontend.index')->withPosts($posts);
}
Please help me out:)
You can get all the tags with loading the posts :
public function index()
{
$tags = Tag::with('posts')->get();
return view('frontend.index')->withTags($tags);
}
In the view you can do something like this :
#foreach ($tags as $tag)
<h2>Tag : {{ $tag->name }}</h2>
#foreach ($tag->posts as $post)
<p>Post : {{ $post->title }}</p>
#endforeach
#endforeach
For geting the posts where you have a tag :
public function index()
{
$tagName = 'new';
$posts = Post::whereHas('tags', function ($q) use($tagName) {
$q->where('name', $tagName);
})->get();
return view('frontend.index')->withTagName($tagName)->withPosts($posts);
}
And in the view you can do this :
<h2>Tag : {{ $tagName }}</h2>
#foreach ($posts as $post)
<p>Post : {{ $post->title }}</p>
#endforeach
If you want to do queries from view you can do it like this (but it's not a god practice because the view is just for viewing the content not geting it from database) :
<?php foreach ((\App\Post::whereHas('tags', function ($q) use($tagName) {
$q->where('name', $tagName);
})->get()) as $post) { ?>
<p>Post : {{ $post->title }}</p>
<?php } ?>
To get all posts with tags with name new, do this:
Post::whereHas('tags', function ($q) {
$q->where('name', 'new');
})->get();
It is solution not perfect answer
You can handle this situation in two ways
1- send two objects from controller to view seprate one for only new tag and second without new tag
2- you can handle this situation in front-end by using conditions
#if($user->tag == "new")
{$user->show}
#endif

Laravel - Many To Many

I have two main tables with relationships many to many and a pivot table.
Tables
Model Product
public function orders()
{
return $this->belongsToMany('App\Order');
}
Model Order
public function products()
{
return $this->belongsToMany('App\Product', 'OrderDetails');
}
And
$orders = Equipment::all();
#foreach($orders as $order)
#foreach($order->products as $product)
{!! $product->name !!} //it works
// How to print the value of the quantity?
#endforeach
#endforeach
What should I do to print the value of the quantity?
Try ->pivot->quantity:
{!! $product->pivot->quantity !!}
Also, add withPivot to a ralationship:
return $this->belongsToMany('App\Product', 'OrderDetails')->withPivot('quantity');
https://laravel.com/docs/5.2/eloquent-relationships#many-to-many

Can't show upload file with eloquent laravel 5

I am bulid website that user can make a post and comment on it. The comment can have many file. Create comment and file work fine but when show the post, that just show post and comment, not with comment's file.
//Post.php
public function commentsPost()
{
return $this->hasMany('App\commentPost');
}
//CommentPost.php
public function post()
{
return $this->belongsTo('App\Post');
}
public function filesPost()
{
return $this->hasMany('App\FilePost');
}
//FilePost.php
public function commentsPost()
{
return $this->belongsTo('App\CommentPost');
}
This my CommentController.php
public function show($id)
{
$post = Post::findOrFail($id);
if ($post != null) {
return view('post.show', compact('post'));
} else {
return redirect('/')->with('error', 'This post does not exist.');
}
}
And show.blade.php
#foreach($post->commentsPost as $comment)
<h2>{{ $comment->message }} by {{ $comment->user->name }}</h2>
#foreach($comment->filesPost->all() as $file)
<h5>{{ $file->filename }}</h5>
#endforeach
#endforeach
I use dd($post->commentsPost->filesPost->all()); and error Undefined property: Illuminate\Database\Eloquent\Collection::$filesPost
How to show the comment also the file? I use Laravel 5
try this
#foreach($post->commentsPost as $comment)
<h2>{{ $comment->message }} by {{ $comment->user->name }}</h2>
#foreach($comment->filesPost() as $file)
<h5>{{ $file->filename }}</h5>
#endforeach
#endforeach

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