【问题标题】:Call to a member function save() on array调用数组上的成员函数 save()
【发布时间】:2019-04-25 10:43:27
【问题描述】:

我正在尝试从表单中获取输入并将其保存到数据库中。该表单包括图像上传。

当我尝试下面的代码时(我知道这都是错误的),我得到“调用数组上的成员函数 save()”。我不确定如何修改代码以使其正确

控制器

    public function store(Request $request){
    //
    $input = $request->all();
    $input->save();
    if($file = $request->file('image')){
      $name = $file->getClientOriginalName();
      if($file->move('image', $name)){
        $post = new Gallery();
        $post->image = $name;
        $post->save();
        return redirect()->route('admin.gallery.index');
      };
    };
}

创建刀片

@extends('layouts.admin')
@section('content')
<h1>UPLOAD PICTURES</h1>
{!! Form::open(['method' =>'POST', 'action'=> 'GalleryController@store', 
'files'=>true, 'enctype'=>'multipart/form-data']) !!}
<div class="form-group">
  {!! Form::label('Picture:') !!}
  {!! Form::file('image', null, ['class'=>'form-control'])!!}
</div>
<div class="form-group">
 {!! Form::label('species_id', 'Species:') !!}
 {!! Form::select('species_id', [''=>'Choose Species'] + $species, null, 
 ['class'=>'form-control'])!!}
</div>
<div class="form-group">
  {!! Form::label('name', 'Image Title:') !!}
  {!! Form::text('name', null, ['class'=>'form-control'])!!}
</div>
<div class="form-group">
  {!! Form::label('patreon', 'Patreon Image?:') !!}
  {!! Form::select('patreon', array(1 =>'Yes', 0=>'No'), 0,['class'=>'form-control'])!!}
</div>
<div class="form-group">
  {!! Form::submit('Upload Image', ['class'=>'btn btn-primary']) !!}
@endsection

型号

namespace App;

use Illuminate\Database\Eloquent\Model;

class Gallery extends Model
{
    //
    protected $fillable = [
      'image',
      'species_id',
      'name',
      'tag',
      'patreon'
    ];
    public function species(){
        return $this->belongsTo('App\Species');
    }
}

【问题讨论】:

  • $input = $request-&gt;all(); $input-&gt;save(); 目的是什么?您没有进行任何更改。而$input 是一个对象数组,而不是您保存到的对象。
  • 错误与$input-&gt;save(); 一致,因为$request-&gt;all() 返回带有post 字段的地图...

标签: php laravel


【解决方案1】:

整个问题都在这个代码块中。

$input = $request->all();
$input->save();

$request-&gt;all(); 从请求中返回一个输入数组。现在$input 是一个数组,为什么你要在一个数组上调用-&gt;save();,我不知道,但如果你删除那行它会起作用。

【讨论】:

    【解决方案2】:

    它说你得到了你的对象,但是在数组中

    $foo = 
    [ 0 => yourObject ]
    

    如果你只有一件物品,那就去做

    $foo = end($foo)

    如果结果数组中有多个项目,只需遍历 foreach 循环即可

    【讨论】:

      猜你喜欢
      • 2017-05-22
      • 1970-01-01
      • 2016-06-29
      • 2020-03-01
      • 2014-03-13
      • 2021-04-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多