使用文章

时间:2017-05-31 22:51:25

标签: php rest file-upload laravel-5

我很确定这是一个noob问题,即使我已经习惯了PHP,但不习惯Laravel

我的目标不能再简单了,我希望能够写一篇文章并添加图片,但即使我让上传系统工作(这不是小菜一碟) ,我在保存文件名本身方面遇到了问题。

以下是我的进展方式:

use App\Photo;
use Illuminate\Http\Request;
use Intervention\Image\Facades\Image;

public function store(Request $request)
{

    $file = $request->file('image');
    $originalname = $file->getClientOriginalName();
    $path = 'uploads/' . $originalname;
    Image::make($file)->save($path);

    $product = new Photo(array(
        'name' => $request->get('name'),
        'image' => $originalname
    ));

    $product->save();

    return \Redirect::route('photo.index', array($product->id))->with('message', 'Product added!');
}

这是我的迁移文件,如果这可以提供帮助:

public function up()
{
    Schema::create('photos', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');
        $table->string('image');
        $table->timestamps();
    });
}

所以我想将文件名保存为数据库中的字符串,以便稍后调用它,就像使用$product->image一样,但是我收到以下错误:

SQLSTATE[HY000]: General error: 1364 Field 'image' doesn't have a default value (SQL: insert into `photos` (`name`, `updated_at`, `created_at`) values (sisdjfposd, 2017-05-31 22:42:18, 2017-05-31 22:42:18))

所以我知道它意味着什么,我不喜欢它,因为它应该有一个值:如果我在行die($originalname);之前添加$product = new Photo array(,我的逻辑上得到我的文件名变量不是空的。

那为什么我会有这个错误?我错过了什么吗?

提前谢谢

1 个答案:

答案 0 :(得分:0)

我认为您错过了将image字段添加到群发作业中。

在你的照片模型中,只需添加:

 protected $fillable = ['name', 'image'];

有关质量分配的更多信息: https://laravel.com/docs/5.4/eloquent#mass-assignment