0

I'm using a MySQL (XAMPP) database, which I have linked in the .env file of my Laravel folder. I'm trying to use the database to show "blog posts" on the posts.index page, and it isn't showing any errors in visual studio code, but when I go to the page in my browser, it shows this error:

Error Class "app\Models\BlogPost" not found http://laravel.test/posts

PostsController

class PostsController extends Controller
{
    public function index()
    {
        return view('posts.index', ['posts' => BlogPost::all()]);
    }

    public function show($id)
    {
        // abort_if(!isset($this->posts[$id]), 404);

        return view('posts.show', ['post' => BlogPost::findorFail($id)]);
    }
}

BlogPost Model

class BlogPost extends Model
{
    use HasFactory;
}

Update: The issue I have now is that I see the item array. (I'm a Laravel beginner, so I don't always see the problems in the code).

This is the post.index code:

@extends('layouts.app')

@section('title', 'Blog Posts')

@section('content')
{{--  @each('posts.partials.post', $posts, 'post')  --}}
@dd($posts)
@forelse ($posts as $key => $post)
    @include('posts.partials.post', [])
     @empty
     No posts found!    
    @endforelse
@endsection

This is what I see in the browser (instead of what's in the database)

  #items: array:1 [▼
    0 => App\Models\BlogPost {#1233 ▼
      #connection: "mysql"
      #table: "blog_posts"
      #primaryKey: "id"
      #keyType: "int"
      +incrementing: true
      #with: []
      #withCount: []
      +preventsLazyLoading: false
      #perPage: 15
      +exists: true
      +wasRecentlyCreated: false
      #escapeWhenCastingToString: false
      #attributes: array:5 [▶]
      #original: array:5 [▶]
      #changes: []
      #casts: []
      #classCastCache: []
      #attributeCastCache: []
      #dates: []
      #dateFormat: null
      #appends: []
      #dispatchesEvents: []
      #observables: []
      #relations: []
      #touches: []
      +timestamps: true
      #hidden: []
      #visible: []
      #fillable: []
      #guarded: array:1 [▶]
    }
  ]
  #escapeWhenCastingToString: false
}
Karl Hill
  • 12,937
  • 5
  • 58
  • 95
nobah
  • 1
  • 5

2 Answers2

0

Your code seems fine. May be it has an issue with namespace in BlogPost model.

if you use this code for Category Model in your PostsController controller:

use App\Models\BlogPost ; then your BlogPost model itself has this namespace

namespace App\Models; Check if your model namespace is still there or not.

0

It's because of using @dd($posts) in blade. Just delete @dd($posts).

ouflak
  • 2,458
  • 10
  • 44
  • 49
Ezio
  • 3
  • 2