Get Posts on index page - php

I'm trying to get posts on Index page using laravel but getting errors.
public function index()
{
$posts = Post::orderBy('created_at', 'desc');
return view('pages.index')->with('posts', $posts);
}
The above snippet defines what I want to do, but, getting this error on index page:
count(): Parameter must be an array or an object that implements Countable
Same snippet works on other pages but it's not working on index page.

Extract the results using get method like so:
$posts = Post::orderBy('created_at', 'desc')->get();

Related

Laravel - Paginate function doesn't working on query building using IF

I am using paginate() on my Controller to pass data to the View. This is my index function using the paginate()
$userData = User::with('jobUnit')
->select('nip','name','address','phone','email','unit_id')
->paginate(10);
return view('users.index', [
'users' => $userData
]);
This is the result:
In the other function, I needed to add some IF conditions on the queries that is look like this:
$keyword = $request->keyword;
$searchedData = User::with('jobUnit')->select('nip','name','address','phone','email','unit_id');
if ($request->searchFilter == 'nip') {
$searchedData->where('nip','like','%'.$keyword.'%');
}
$searchedData->paginate(10);
The results is different, which is a problem for me because I am using the pagination links in the View. Here is the results:
Does the pagination() not working? Because I tried using the get() as well which should returns "Collection", but it was still returning the "Builder" results.
you need another variable to store the return data
$searchDataPaginated = $searchedData->paginate(10);
or using the current one if you want
$searchedData = $searchedData->paginate(10);

Can't access object field after eager loading in Laravel 8

When I'm trying to eager load my Model with relation like that:
$plants = Plant::with('history')
->get()
->where('user_id', auth()->id());
I want to modify those extracted dates with my function like that:
foreach ($plants as $plant) {
$plant->watered_at = self::getDateForHumans($plant->history->watered_at);
$plant->fertilized_at = self::getDateForHumans($plant->history->fertilized_at);
}
I get this kind of error:
ErrorException
Trying to get property 'watered_at' of non-object
but if I try to debug it by dd() function i get a positive result
dd(self::getDateForHumans($plant->history->watered_at));
dd() result
Does anybody know how to fix it or what is the workaround?
seems your history has no watered_at member, so it comes to this error.
Check first if you can access this member with
if(isset($plant->history->watered_at)){
$plant->watered_at = self::getDateForHumans($plant->history->watered_at);
}

In laravel, get an errror when show the product items

I want to get some view data using laravel. here is my code:
public function brandsview($cate_url, $brand_url)
{
$brands = Brands::where('url',$brand_url)->first();
$brand_id = $brands->id;
$products = Products::where('brand_id',$brand_id)
->where('status','!=','Hide')
->where('status','Show')
->get();
return view('lokalproductspage.brands')
->with('brands', $brands)
->with('products', $products);
}
I get the error trying to get property 'id' of non-object. Please help me.
Looks like $brands return nothing, are you checked it?
If return of $brands is not stable may be u should add some checks before use attributes like 'id'
Change first() to firstOrFail(), which will let you know if you actually found a record. Normally your error suggests there was no record found. It is a nice way to show a 404 if the user put a bad url in.
$brands = Brands::where('url',$brand_url)->firstOrFail();

Laravel orderBy date is not working when using paginator

I am new to laravel and am struggling to figure this one out.I am trying to order my posts by date and also use the paginator. Whenever I remove the paginator. it orders by date, but adding it back in orders by id, I think?
My model
class Post extends Model
{
//
protected $dates = ['date'];
}
My controller method
public function show()
{
$posts = Post::orderBy('date','desc')->get();
return view('welcome',['posts' => Post::paginate(5)], compact('posts'));
}
You're essentially retrieving all posts and then paginating them, after retrieving all posts and ordering them.
Your code breaks down like this:
public function show()
{
// retrieve posts and order them by date
$posts = Post::orderBy('date','desc')->get();
// retrieve posts again and paginate them
return view('welcome',['posts' => Post::paginate(5)], compact('posts'));
}
You have two options --
Get posts, order them, paginate them, and store them in a variable that you pass to your view:
public function show()
{
$posts = Post::orderBy('date','desc')->paginate(5);
return view('welcome', compact('posts'));
}
Or get the posts, order them and paginate them while passing them to the view:
public function show()
{
return view('welcome',[ 'posts' => Post::orderBy('date','desc')->paginate(5) ]);
}
You can use other column/s specifically the created_at or updated_at. I tried my customized column datetime as my orderingBy but it doesn't worked, so I used another column(updated_at) wherein I just want to get the updated records descendingly and I noticed that it can be use as my solution and it works fine in my query.
->orderBy('updated_at','DESC')->get();
->orderBy('created_at','DESC')->get();

Paging in PHP Laravel

I am trying to make a paging in Laravel, but i keep getting errors.
I try put
->paginate(3)
On the return, but i keep getting errors like Call to undefined method Laravel\Paginator::get() and Call to undefined method Laravel\Paginator::order_by()
public function get_index()
{
$categories = Category::all();
return View::make("stories.index")
->with("title","Sexnoveller")
->with("categories", $categories)
->with("stories", DB::table('stories')
->order_by('id', 'desc')->get());
}
To use pagination call paginate() instead of get(). In your case that would be:
return View::make("stories.index")
// ...
->with("stories", DB::table('stories')
->order_by('id', 'desc')->paginate(3));
Then in the view just remember to iterate over $stories->results.
I do recommend to create a model for that Stories table. Once done, you could do something like:
Story::orderby('story_name', 'ASC')->paginate(10);

Categories