Laravel-找不到模型类 [英] Laravel - Model Class not found

查看:691
本文介绍了Laravel-找不到模型类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

开始使用模型时,出现以下错误

When starting to work with models I got the following error

找不到类帖子.".

Class Post not found`.

我所做的一切:
-使用命令php artisan make:model
创建模型 -尝试使用echo Post::all()

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()

我使用了以下代码:

router.php

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

Post.php

<?php 
namespace App;

use Illuminate\Database\Eloquent\Model;

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

我尝试了什么
-重命名类
-转储自动加载(​​未找到Laravel 4模型类)

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

推荐答案

Laravel 5促进了命名空间的使用用于模型和控制器.您的模型位于App命名空间下,因此您的代码需要这样调用:

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 = \App\Post::all();
        return $results;
});

如评论中所述,您还可以use或将名称空间导入文件中,因此您无需引用完整路径,如下所示:

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 App\Post;

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 App\Post as PostModel;

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

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

此处有关导入和别名命名空间的更多信息: http://php.net/manual/zh/language.namespaces.importing.php

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

这篇关于Laravel-找不到模型类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆