Laravel 创建方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27293177/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 10:30:54  来源:igfitidea点击:

Laravel create method

phplaravellaravel-4

提问by Naveen Gamage

I'm trying to store an array using Laravel's createmethod

我正在尝试使用 Laravel 的create方法存储数组

$input = Input::all();
$new_media = $this->media->create($input);

or

或者

$input = Input::all();
$new_media = Media::create($input);

both codes does not work.

两个代码都不起作用。

This is the error I'm getting.

这是我得到的错误。

Method [create] does not exist.

Laravel documentation here http://laravel.com/docs/4.2/eloquent

Laravel 文档在这里http://laravel.com/docs/4.2/eloquent

From laravel docs

来自 Laravel 文档

// Create a new user in the database...
$user = User::create(array('name' => 'John'));

Media Model

媒体模型

<?php

class Media extends Eloquent {

    protected $table = 'media';

    protected $guarded = array();

    public static $rules_video = array(
        'title' => 'required',
        'url' => 'required'
    );
    public static $rules_image = array(
        'title' => 'required'
    );

    public function category(){
        return Category::find($this->category_id);
    }

}

回答by Marwelln

You need to setup Mass Assignmentswhen using create, fillor update. See this answer.

使用,或时需要设置批量分配。看到这个答案createfillupdate

Remove your guardedproperty and create a new one called fillableas an array with the allowed fields to be updated with mass assignments.

删除您的guarded属性并创建一个名为fillable数组的新属性,其中允许使用批量分配更新的字段。

protected $fillable = ['title', 'url'];