Laravel displaying all posts with WHERE clause and pagenation in laravel - php

so i want to display post in my index page but only the posts that are reviewed by the admin. so i added another column in my database table post which is called "review" which is integer. So this is what i have in hand.
in my controller i have this
public function index()
{
$this->layout->content = View::make('partials.index',
array(
'posts' => Post::paginate(9)
));
}
and in my index page i have this
#section('content')
<div class="dashboard">
#foreach (array_chunk($posts->getCollection()->all(),2) as $row)
<div class="row">
#foreach($row as $post)
<article class="col-md-4 effect4" id="dash-box">
<p></p>
<c>{{$post->content}}</c><br>
<b>{{$post->title}}</b><br>
<d>posted..{{$post->created_at->diffForHumans()}}</d>
<hr>
</article>
#endforeach
</div>
#endforeach
<div class="page">
{{$posts->appends(Request::only('difficulty'))->links()}}
</div>
</div>
#stop
Help im newbie here i hope someone can help me out with this one hoping for a reply thanks

Just call:
Post::whereReview(1)->paginate(9);

Please read the documentation (and also the one for the query builder since these pages apply to Eloquent as well)
You can just add a where() call to the query:
$posts = Post::where('review', '=', 1)->paginate(9);
Or a shorter version (= is the default operator)
$posts = Post::where('review', 1)->paginate(9);
Or even with a dynamic method name:
$posts = Post::whereReview(1)->paginate(9);
Also you can use true instead of 1. Laravel will convert it:
$posts = Post::whereReview(true)->paginate(9);
There is also no need to do chunking that complicated:
#foreach (array_chunk($posts->getCollection()->all(),2) as $row)
You can just use the chunk method on any collection:
#foreach ($posts->chunk(2) as $row)

Related

select id from post table where title=$title

i have post table and i have comment table i have made them with laravel
i made a IndexController and it has a method that returns all of my posts by their title;
i also return and compact comment of each post and show them under each post content but i have to pass the post id to comment table by myself
for example i have a post with id=7 and i have to pass the 7 to post_id column of comment table
i have to write a query something like this
select id from posts where title=$title
with this query i want to select post id by post title and pass it to post_id in my comment table
this my index controller
public function single($title)
{
$posts = Post::where('title', $title)->get();
$comments = Comment::where([
['post_id', 7],
['verify',1]
])->orderBy('id', 'desc')->get();
return view('main.single', compact('posts', 'comments'));
}
this is comment controller
public function store(Request $request)
{
Comment::create([
'post_id' => $request['post_id'],
'user_id' => Auth::user()->id,
'message' => $request['message'],
]);
}
and also this my single blade file code
#foreach($comments as $comment)
<div class="container">
<div class="bg-secondary bg-opacity-10 p-3 mb-4">
<div>
<p class="fw-bold">{{$comment->user->first_name.' '.$comment->user->last_name}}
<br>
<span class="text-muted text-small-14 fw-light">{{$comment->created_at}}</span>
</p>
</div>
<div class="mt-0">
</div>
<div>
{{$comment->message}}
</div>
</div>
</div>
#endforeach
and also i use laravel 8
You can do the following if you don't want to pass by yourself, assuming your relationships are correct. If not, feel free to include them in your current question, and I can help with those too.
public function single($title)
{
$post = Post::with(['comments' => function ($query) {
$query->where('verify', 1)->orderBy('id', 'desc');
}])->where('title', $title)->first();
return view('main.single', compact('post'));
}
This will allow you to pass just a post to your blade view.
Now instead of
#foreach($comments as $comment)
You can
#foreach($post->comments as $comment)

Beginner in Laravel - Eager loading seems to not work?

I'm new to Laravel and I'm trying to make a post where the user's post can receive likes from other users. But I'm trouble at when you click the user, it was suppose to direct to the users page where you can see all its post and the likes the it received. This is the code that suppose to do that work:
This is the controller:
public function index(User $user)
{
$posts = $user->posts()->with('user', 'likes')->get();
return view('users.posts.index', [
'user' => $user,
'posts' => $posts,
]);
}
}
and this is the view/template:
<div class="flex justify-center">
<div class="w-8/12 bg-white p-6 rounded-lg">
{{$user->name}}
</div>
</div>
I don't know what's the problem though, or is it a bug with Laravel eager loading?
But unfortunately it only returns a blank page, there's no error though.
The thing is after putting this code inside dump and die, there's data showing from the database. I don't why it doesn't show. Can someone help me with this problem? Much appreciated
Following this tutorial: https://www.youtube.com/watch?v=MFh0Fd7BsjE
Tutorial Github: https://github.com/codecourse/posty-traversy-media
If you want to access the posts you can iterate through them:
#foreach($posts as $post)
{{ $post->title }}
{{ $post->likes->count() }}
#endforeach
Not sure what data or relationships you want to access.
Check your route whether it has a user id for model injection
eg:/index/{user}
also in your blade example, there is no posts are used.you are using the user object
public function index(User $user)
{
$posts = $user->posts()->with('user', 'likes')->get();
return view('users.posts.index')->with([
'user' => $user,
'posts' => $posts,
]);
}

How Would I Send Data To a Controller

I'm building a forum, and I'm trying to implement a categories page. The page is working as of now, it's dynamic so it lists all categories stored in the database. However I want to be able to click on a category and be taken to a template page. From this template page I want to pass a category ID (defined in the database as a primary key). Then all posts with the matching category ID will be displayed. I'm having trouble passing this category ID to my category page template.
Any help would be extremely appreciated!
(How categories are displayed in a list:)
#foreach($categories as $row)
<div id="newscontainer" class="container">
<?php $categoryid = $row->id; ?>
<span id='categoryname'><?= $row->categoryname ?><br></span>
<span id="categorydescription"><?= $row->categorydescription?></span>
</div>
<br>
#endforeach
Thanks!
First of all define a route in web.php:
web.php:
Route::get('category/{category}','YouController#YourCatFunction')->name('categories.list');
in your controller:
public function YourCatFunction(Category $category)
{
// here you can return view for post with that category and then display them
return $category;
}
then in your view:
#foreach($categories as $row)
<div id="newscontainer" class="container">
<span id='categoryname'>{{ $row->categoryname }}<br></span>
<span id="categorydescription">{{ $row->categorydescription }}</span>
</div>
<br>
#endforeach
You can create a web route which will handle the category calls and return the view with that category and it's posts.
First you create a route like this:
Route::get('category/{category}', 'CategoriesController#show')->name('category.show');
Then you can access this Category inside the controller and load the posts and return them like this:
public function show(Request $request, Category $category) {
return view('category.show', compact('category'));
}
Then in your view you would have something like this where you loop over available posts:
#foreach($category->posts as $post)
// do something
#endforeach
To call the route you can simply create this link:
Show
As I can see, your base namespace is ULMG, so the correct way to your Category class would be ULMG\Category
You can try this one as well.
Route web.php
Route::get('category/{categoryid}', ['as'=>'category.show','uses'=>'CategoriesController#show');
Controller CategoriesController.php
public function show($categoryid){
// some of your code.
$categoryid = DB::table('category')->select('categoryId');
return view('category.show', compact('categoryId'));
// don't forget if you have some variables and you want to view it at blade just put it inside the compact
}
View blade category.show.blade.php
#foreach($categories as $row)
<div id="newscontainer" class="container">
<span id='categoryname'>{{ $row->categoryname }}<br></span>
<span id="categorydescription">{{ $row->categorydescription }}</span>
</div>
#endforeach
For anyone else who is having the same issue:
(I had a eureka moment...)
My forums.blade.php file (where the user selects the category they want to view:
Here, it's calling the category route (which is where the posts will be displayed) then it's setting the category ID in one url. It will look like this in the browser: www.example.test/category/(ID) (so when I query the database for posts under that category it will extract them).
<span id='categoryname'><?= $row->categoryname ?><br></span>
My web.php file:
I basically grabbed the id from the URL which was passed through when the user clicked on the link.
Route::get('/category/{id}', 'CategoriesController#getid');
My CategoriesController.php file:
Here I have defined a function, so in the web.php it knows to go to the function with the attribute of getid. Once it has found the correct function it sets the $catid the same value as $id. Then it returns to the categorytemplate view (which is the template requiring the ID in the first place to display the posts) with the $catid variable in a compact function.
public function getid($id){
$catid = $id;
return view('categorytemplate', compact('catid'));
}
I hope my explanation is clear enough to understand. And I hope this can help someone else with this issue in the future!
Thanks again to everyone else suggesting ideas.

Laravel Pass Comments with Posts

I have a One to Many relationship set up for my "announcements" having many "comments".
Currently, when my user loads up the app page, I have it send the 30 most recent announcements like such:
Route::get('/app', function () {
$posts = Announcement::take(30)->orderBy('id', 'desc')->get();
return View::make('app')->with([
//posts
'posts' => $posts,
//orders
'orders' => $orders
]);
}
When I echo out the announcements in blade using a foreach loop through the $posts object, I want to also echo out the comments for each post under the respective post.
Is it possible to pass the comments for a post as part of the actual post object? For example, it would be nice if I could do this:
#foreach ($posts as $post)
//echo out the post
{{$post->content}}
//echo out the comments relating to this post
{{$post->comments}}
#endforeach
#Amr Aly gave you the right answer, and I would like to add on top of it.
When you loop through your comments as he showed you (and you should), it will make a different query for each comment. SO if you have 50 comments, that's 50 more queries.
You can mitigate that by using eager loading
$posts = Announcement::with('comments')
->take(30)->orderBy('id', 'desc')
->get();
Then just loop the way he showed you. THis will limit the queries to 2 only. You can read more from the docs here: https://laravel.com/docs/5.4/eloquent-relationships#eager-loading
You can add another foreach for your comment like this:
#foreach ($posts as $post)
//echo out the post
#if($post->comments->count())
#foreach ($post->comments as $comment)
// {{ $comment }}
#endforeach
#endif
#endforeach

Issue in fetching data from db to the views in laravel 5.2

Im new to laravel and studying it by creating some test projects myself in laravel 5.2. But i got stuck now with some issue in fetching data correctly from db in laravel 5.2 and display the result. I have a menu table in my db with fields -> id, menutype, itemname, itemprice, itemimage with some datas in it. I want to display it on my webpage in a specific way like as seen on the below given screenshot.
See:
And this one is my db table screenshot with the values on it. See:
i added the below codes in my Controller (GuestController.php)
public function menu() {
$result=DB::table('menu')->select('menutype')->distinct()->get();
return view('guest.menu')->with('data',$result);
}
and in the View (menu.blade.php), i had given the below code:
<div class="row">
#foreach($data as $row)
<div class="col-1-3">
<div class="wrap-col">
<h3>{{$row->menutype}}</h3>
<?php
$item=DB::table('menu')->where('menutype', $row->menutype)->get();
?>
#foreach($item as $row)
<div class="post">
<img src="assets/images/{{$row->itemimage}}"/>
<div class="wrapper">
<h5>{{$row->itemname}}</h5>
<span>Rs.{{$row->itemprice}}/-</span>
</div>
</div>
#endforeach
</div>
</div>
#endforeach
</div>
This works perfectly and i am getting the desired output as seen on the products page screenshot given above. But i know this method is not correct, because i am giving the query statement on the View itself like as given below to fetch data and its against the MVC concept:
<?php $item=DB::table('menu')->where('menutype', $row->menutype)->get(); ?>
So is there any other simple and better way i can implement to get the above said desired output along with keeping the MVC Standards?? Please help! Thanks in advance...
Laravel's Collection can really help you out with this. Specifically, the groupBy method. First, you get all of the menu items with all the data. Then, you use the groupBy method on the Collection to group the menu items into separate arrays based on their menutype. You can then use this one Collection to do all the work in your view.
The code is shown below. You can combine a couple of the lines into one if you'd like, but it is broken out into multiple lines to show all the steps:
public function menu() {
// get all the menu items
$menuArray = DB::table('menu')->get();
// create a Laravel Collection for the items
$menuCollection = collect($menuArray);
// group the Collection on the menutype field
$groupedMenu = $menuCollection->groupBy('menutype');
/**
* Note that Eloquent queries (using Models) will automatically return
* Collections, so if you have your Menu model setup, your first two
* lines would just be:
* $menuCollection = Menu::get();
* or, all three lines could be combined into:
* $groupedMenu = Menu::get()->groupBy('menutype');
*/
// pass the grouped Collection to the view
return view('guest.menu')->with('data', $groupedMenu);
}
Now, in your view, your outer foreach will iterate through the groups. The inner foreach will iterate through the items in each group:
<div class="row">
#foreach($data as $type => $items)
<div class="col-1-3">
<div class="wrap-col">
<h3>{{$type}}</h3>
#foreach($items as $item)
<div class="post">
<img src="assets/images/{{$item->itemimage}}"/>
<div class="wrapper">
<h5>{{$item->itemname}}</h5>
<span>Rs.{{$item->itemprice}}/-</span>
</div>
</div>
#endforeach
</div>
</div>
#endforeach
</div>

Categories