dtlh12053 2018-05-13 07:34
浏览 260

Laravel:使用来自多个模型的属性填充表单

I am trying to build a form to edit the information of offices. This form is build using information coming from two models: Office and Address. Like you see in the image fields marked with 1 belongs to address model, the ones marked with 2 belongs to Offices

enter image description here

An Office has one Address

office.php

public function address()
{
    return $this->hasOne('App\Address');
}

An address belongs to an Office

address.php

public function office()
{
    return $this->belongsTo('App\Office');
}

Now, in order to populate the edit view I need to bind two models to a form!

I have tried this:

{!! Form::model($element, ['method'=>'PATCH', 'action'=> ['AdminofficeController@update', $element->slug ],'files'=>true]) !!} 

{!!Form::label('image', 'Upload a Featured Image') !!}
{!!Form::file('image', null, array('class' => 'form-control'))!!}

...here fields from office model...

{!! Form::label('street', 'Street:', array('class' => 'pt-3'))!!}
{!! Form::text($element->address->street, null, array('class'=>'form-control' )) !!}
 ... here other fields ...

{!!Form::submit('Edit Büro', array('class' => 'btn btn-success btn-block')) !!}
{!!Form::close() !!} 

But I get the following error:

Property [street] does not exist on this collection instance. (View: C:\laragon\www\domainesources\views\dashboard\bueros\edit.blade.php)

This line does not solve the problem

{!! Form::text($element->address->street, null, array('class'=>'form-control' )) !!}

I have var_dump te collection and indeed, it has an street property, it means the relation is working ok.

As far as I know I can't bind two models to one form (not in HTML)

How do I populate a form with properties coming from multiple models?

I would hate to make two forms one to edit Address and another for the name of the office.

  • 写回答

1条回答 默认 最新

  • dongquan0024 2019-06-18 19:06
    关注

    This question is old but here's an answer that works for me.

    Your first form line:

    {!! Form::model($element, ['method'=>'PATCH', 'action'=> ['AdminofficeController@update', $element->slug ],'files'=>true]) !!} 
    

    should be amended to:

    {!! Form::model($building->toArray() + $address->toArray(), ['method'=>'PATCH', 'action'=> ['AdminofficeController@update', $element->slug ],'files'=>true]) !!} 
    

    I'm not 100% certain that the ->toArray() is required but this does work for forms that I have with multiple models that I want to be auto-populated.

    Note: the $building and $address variables would be whatever you have used in your code.

    评论

报告相同问题?

悬赏问题

  • ¥15 BP神经网络控制倒立摆
  • ¥20 要这个数学建模编程的代码 并且能完整允许出来结果 完整的过程和数据的结果
  • ¥15 html5+css和javascript有人可以帮吗?图片要怎么插入代码里面啊
  • ¥30 Unity接入微信SDK 无法开启摄像头
  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算