Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
230 views
in Technique[技术] by (71.8m points)

php - Laravel - Model Class not found

When starting to work with models I got the following error

Class Post not found`.

All I did:
- Created a Model with the command php artisan make:model
- Tried to get all entries from table posts with echo Post::all()

I used the following code:

router.php

Route::get('/posts', function(){
    $results = Post::all();
    return $results;
});

Post.php

<?php 
namespace App;

use IlluminateDatabaseEloquentModel;

class Post extends Model {
    protected $table = 'posts';    
}

What I tried
- Renaming Class
- Dump-autoload (Laravel 4 Model class not found)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Laravel 5 promotes the use of namespaces for things like Models and Controllers. Your Model is under the App namespace, so your code needs to call it like this:

Route::get('/posts', function(){

        $results = AppPost::all();
        return $results;
});

As mentioned in the comments you can also use or import a namespace in to a file so you don't need to quote the full path, like this:

use AppPost;

Route::get('/posts', function(){

        $results = Post::all();
        return $results;
});

While I'm doing a short primer on namespaces I might as well mention the ability to alias a class as well. Doing this means you can essentially rename your class just in the scope of one file, like this:

use AppPost as PostModel;

Route::get('/posts', function(){

        $results = PostModel::all();
        return $results;
});

More info on importing and aliasing namespaces here: http://php.net/manual/en/language.namespaces.importing.php


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...