gpt4 book ai didi

php - 在 Laravel 5 中将数据保存到数据库中

转载 作者:可可西里 更新时间:2023-11-01 12:16:45 25 4
gpt4 key购买 nike

首先

我写了一个迁移脚本。


第二

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


数据库

现在,我的数据库中有一个 subscribes 表。 它有 2 个字段: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);
}

}

Controller

<?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。看来我的命名空间有问题。

这个命名空间现在让我有点困惑。有人可以澄清或解释一下吗?

不胜感激。

提前致谢。

最佳答案

这里是对命名空间如何在 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.
}
}

关于php - 在 Laravel 5 中将数据保存到数据库中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29776773/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com