Home > Enterprise >  count(): Argument #1 ($value) must be of type Countable|array, null given ORM
count(): Argument #1 ($value) must be of type Countable|array, null given ORM

Time:08-14

PostsController:

<?php

       namespace App\Http\Controllers;

     use Illuminate\Http\Request;
      use Illuminate\Support\Facades\Storage;
      use Intervention\Image\Facades\Image;
        use App\Models\Post;


                 class PostsController extends Controller
            {
     
                      public function index()
             {
    $posts = Post::orderBy('created_at','desc');
      return view('pages.index')->with('posts', $posts);
}

index.blade.php

    <h1>Posts</h1>
@if(count($posts) > 0)
    @foreach($posts as $post)
        <div >
            <div >
                <div >
                    <img style="width:100%" src="/storage/cover_images/{{$post->cover_image}}">
                </div>
                <div >
                    <h3><a href="/posts/{{$post->id}}">{{$post->title}}</a></h3>
                    <small>Written on {{$post->created_at}} by {{$post->user->name}}</small>
                </div>
            </div>
        </div>
    @endforeach
@else
    <p>No posts found</p>
@endif

when i go to website it pops up error and i do not know what should i do. Actually there is one question with this title which i have but actually it did not help me.

CodePudding user response:

Laravel provide much better solution for this kind of scenario, use forelse

@forelse ($posts as $post)
    ...
@empty
    <p>No posts found</p>
@endforelse

Please the blade document.

CodePudding user response:

You forget to put get() to your query

<?php

       namespace App\Http\Controllers;

     use Illuminate\Http\Request;
      use Illuminate\Support\Facades\Storage;
      use Intervention\Image\Facades\Image;
        use App\Models\Post;


                 class PostsController extends Controller
            {
     
                      public function index()
             {
    $posts = Post::orderBy('created_at','desc')->get();
      return view('pages.index')->with('posts', $posts);
}

Check the offical docs for using Count() https://www.php.net/manual/en/function.count.php

CodePudding user response:

Can you do a "dump" of your "$posts" and see what do you have?

Before using "count" function, i recommend to check the type of your "$posts" or doing something like:

$posts = Post::orderBy('created_at','desc') ?? [];

Or make it more simple by adding a return type on your "orderBy" function like

public static function orderBy(...) : Array {}

Another related issue which can help: https://stackoverflow.com/a/69055096/7186622

  • Related