Laravel 5.2 将令牌和 created_at 值输入数据库

Laravel 5.2 enter token and created_at values into database

Laravel 5.2 似乎发生了一些巨大的变化。为旧版本提供的解决方案似乎不起作用。理想情况下,令牌、created_at 和 updated_at 的值应该在每个插入命令中自动输出。那么这应该怎么做呢?当当前代码为运行时,这3列没有插入任何值。这是控制器中的代码:

public function showCustomer(Request $request){
    $nameCheck = DB::table('customers')->select("customer_name")->where("customer_name",$request->name)->get();
    $response = array();
    if(count($nameCheck) > 0){
        $response["success"]="0";
    } else {
        $data = array(
            "customer_name" => $request->name,
            "age" => $request->age,
            );

        if(DB::table('customers')->insert($data)){
            $response["success"]="1";
        } else {
            $response["success"]="-1";
        }
    }
    echo json_encode($response);
}

这是模型的代码

namespace App;
use Illuminate\Database\Eloquent\Model;

class Customers extends Model{

}

表单代码

<div class="customer-form">

{!! Form::open(array('url'=>"customer")) !!}
{!! Form::label("Customer Name: ") !!}
{!! Form::text('name', null, array('class'=>'form-control','placeholder'=>"Your name")) !!}
{!! Form::label("Age: ") !!}
{!! Form::number('age', null, array('class'=>'form-control','placeholder'=>"Age")) !!}
{!! Form::submit('submit', array('class'=>'form-control')) !!}
{!! Form::close() !!}

</div>

这是创建代码 table:

    public function up()
{
    Schema::create('customers', function (Blueprint $table) {
        $table->increments('customer_id');
        $table->string('customer_name');
        $table->integer('age');
        $table->timestamps();
        $table->rememberToken();
    });
}

当您 insert/update 数据直接使用 DB façade 时,不会应用额外的 update/insert 逻辑 - 只有您告诉数据库层执行的操作才会实际执行。在您的情况下,您只插入指定 customer_nameage.

的行

为了使用 Laravel 模型的内置时间戳功能,您需要像这样执行数据库 insert/update 交互:

$newCustomer = new Customers($request->all());
$newCustomer->save();

您还需要在模型中指定可批量分配的字段,以便能够批量保存它们(在我的示例中为构造函数参数):

class Customers extends Model {
    protected $primaryKey = 'customer_id';

    protected $fillable = [
        "customer_name", "age"
    ];
}

当您将 table 主键命名为 'id' 以外时,您还需要像我上面那样在模型中指定它。

您没有特别要求,但我已经重写了您的 showCustomer 方法,以向您展示更简洁的代码以及如何以 "Laravel" 方式完成。

public function showCustomer(Request $request){
    $customer = Customer::select("customer_name")
        ->where("customer_name",$request->name)
        ->first();

    if($customer){
        return response()->json(['success' => 0]);
    }

    $customer = new Customer;
    $customer->name = $request->name;
    $customer->age = $request->age;
    $customer->token = str_random(50);

    if ($customer->save()) {
        return response()->json(['success' => 1]);
    }

    return response()->json(['success' => -1]);
}

这里有几点需要注意:

  1. 如果没有一些额外的配置,记住令牌不会自动设置。您可以使用特殊方法使其在保存时更新,但我发现使用 str_random() 自己设置它更容易,如上所示。

  2. 模型应该是单词的单数形式,因此您应该将模型从 Customers 更改为 Customer。此外,您的主键应该只是 id 而不是 customer_id

  3. 为了使 created_at 和 updated_at 时间戳起作用,您可能需要通过模型引用它们(如修改后的 showCustomer 方法)而不是通过 DB::table().