多对多 Laravel 5.1,不工作,参数不匹配(字符串,数组)

Many to many Laravel 5.1, not working, parameter mismatch (string, array)

我正在学习本教程 https://laracasts.com/series/laravel-5-fundamentals/episodes/21,但无法使我的多对多迁移正常工作。事不宜迟,这里是代码:

迁移:

创建位置

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

创建位置类型

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

创建枢轴tablelocation_locationtype

    Schema::create('location_locationtype', function (Blueprint $table) {
        $table->integer('location_id')->unsigned();
        $table->integer('locationtype_id')->unsigned();
        $table->timestamps();
    });

型号:

位置类型

class Locationtype extends Model
{
  protected $table = 'locationtypes';
  protected $fillable = ['name'];
  public function locations()
  {
    return $this->belongsToMany('App\Location')->withTimestamps();
  }
}

位置

class Location extends Model
{
  protected $table = 'locations';
  protected $fillable = ['name'];
  public function locationtypes()
  {
    return $this->belongsToMany('App\Locationtype')->withTimestamps();
  }
}

LocationController@store

public function store(Requests\LocationRequest $request)
{
    $location = Location::create($request->all());
    $location->locationtypes()->attach($request->input('locationtype'));
}

输出:preg_replace(): Parameter mismatch, pattern is a string while replacement is an array。我不知道它试图用数组替换哪个字符串(我想是 $request->input('locationtype').

如果我添加为:

public function store(Requests\LocationRequest $request)
{
    dd($request->input('locationtype'));
}

我得到:

array:2 [
  0 => "1"
  1 => "3"
]

这很好,因为我 select 编辑了第一和第三 Locationtype。如果我不 select 任何位置类型,数组将为空,并且不会有错误。

此外,如果我将函数更改为:

public function store(Requests\LocationRequest $request)
{
    Location::create($request->all());
}

只要我的表单中有以下元素,我仍然会遇到同样的错误。

表单元素:

<div class="form-group">
    {!! Form::label('locationtype', 'Type of location') !!}
    {!! Form::select('locationtype[]', $locationtypes, null, ['class' => 'form-control', 'multiple']) !!}
</div>

$locationtypes 给出正确的值。

谢谢大家,如果需要更多信息,请索取。

编辑:

如果我将函数更改为

    $location = new Location;
    $location->locationtypes()->attach($request->input('locationtype'));

枢轴 table 被填满。所以问题在于用 $request->all();.

创建新的 Location

替换

Location::create($request->all());

$location = Location::create($request->except('locationtype'));

经过一些推导和反复试验,我得出了它。如果有人发表评论并解释出了什么问题以及为什么我需要排除 locationtype.

,我将不胜感激

HF 所有,编码良好。