将数据保存到Laravel 5中的数据库中

时间:2015-04-21 15:34:04

标签: php database laravel laravel-5

第一

我写了一个迁移脚本。


第二

我运行php artisan migrate将表迁移到我的数据库中。


数据库

现在,我的数据库中有一个subscribes表。  它有两个字段:idemail

enter image description here


路线

Route::post('/subscribe', array('as' =>'subscribe','uses'=>'AccountController@postSubscribe'));


模型

<?php namespace App;

use Illuminate\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Model;

class Subscribe extends Model {

    protected $table = 'subscribes';


    //Validation Rules and Validator Function
    public static function validator($input){

        $rules = array(
            'email'    =>'required|email'
        );

        return Validator::make($input,$rules);
    }

}

控制器

<?php namespace App\Http\Controllers;

use Input, Validator, Auth, Redirect;

class AccountController extends Controller {

    public function postSubscribe() {

            $subscribe        = new Subscribe; <-------- Line#46 (BUG HERE)
            $subscribe->email = Input::get('email');
            $subscribe->save();

            dd("Hi");

            return Redirect::to('/')
                ->with('success','You have been successfully subscribe to us.');

        }
}

?>

错误

enter image description here


问题

为什么我不能$subscribe = new Subscribe;

使用Laravel 5 数据插入数据库的最佳做法是什么?


更新

感谢@Mark Ba​​ker。 我的命名空间似乎有问题。

这个namspacing现在对我来说有点混乱。 有人澄清或解释一下吗?

感激不尽。

提前致谢。

3 个答案:

答案 0 :(得分:8)

以下是关于命名空间如何在PHP中工作的高级概述,以帮助您理解这一点并为您提供问题的解决方案。

<?php

// This is the namespace of this file, as Laravel 5 uses PSR-4 and the
// App namespace is mapped to the folder 'app' the folder structure is
// app/Http/Controllers
namespace App\Http\Controllers;

// Use statements. You can include classes you wish to use without having
// to reference them by namespace when you use them further on in this
// namespaces scope.
use App\Subscribe;

class MyController extends BaseController 
{
    public function postSubscribe()
    {
        // You can now use the Subscribe model without its namespace
        // as you referenced it by its namespace in a use statement.
        $subscribe = new Subscribe();

        // If you want to use a class that is not referenced in a use
        // statement then you must reference it by its full namespace.
        $otherModel = new \App\Models\Other\Namespace\OtherModel();

        // Note the prefixed \ to App. This denotes that PHP should get this
        // class from the root namespace. If you leave this off, you will
        // reference a namespace relative to the current namespace.
    }
}

答案 1 :(得分:1)

您可以试试这个,只需使用它:

$subscribe        = new App\Subscribe;

答案 2 :(得分:0)

使用App\Subscribe;

然后您可以在代码中使用$subscribe = new Subscribe;