3

I have added the line use App\Post; in the header of my PostController class.

When I try $post = new App\Post; in a controller method, I get the following error message

Class 'App\Http\Controllers\App\Post' not found

What are some possibilities for why I am getting this error message?

1
  • 3
    Just try $post = new Post(); Commented Feb 7, 2016 at 4:02

4 Answers 4

2

Since you already included the Post class, you don't have to reference the path again.

$post = new Post();

This should work.

Sign up to request clarification or add additional context in comments.

1 Comment

just complementing the answer, you don't need to Specify the entire namespace of the class "App\Post" if you already declared the "use App\Post;" - So with that, you just need to use "Post" to call the class
0

u can use facades..

$post = Post::all(); << return all row

1 Comment

try to explain some more. How will this help the OP and what was/is wrong with the current situation.
0

I am assuming you used artisan to generate the Model. You may use eloquent as:

use App\Post as Post;
...
$post = Post::all();

Comments

0

The reason you are not able to access the model via App\Post is because the file you are attempting to do this in already has a namespace, shown in the error: App\Http\Controllers\App\Post, which implies the namespace of the file is App\Http\Controllers.

Since you are not referencing the model with an absolute namespace (\ at the beginning), PHP is looking for that class relative to the current namespace.

<?php

namespace App\Http\Controllers;

...

$post = App\Post::find(1);    // App\Http\Controllers\App\Post

$post = \App\Post::find(1);   // App\Post

That explains the error. However, as mentioned by others, you have already used the model in your file and can access it simply with Post.

$post = Post::find(1);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.