【问题标题】:HasMany relationship old inputHasMany 关系旧输入
【发布时间】:2013-09-29 18:21:51
【问题描述】:

我有一个模型类别。类别有很多本地化。当我存储类别时,我有这些输入:

{{ Form::text('title[en]', Input::old('title')) }}
{{ Form::text('title[ru]', Input::old('title')) }}

我这样存储在我的控制器中:

        // Gett all inputs
        $inputs = Input::all();

        // Create resource
        $item = Category::create([]);

        // Create localization
        foreach(Input::get('title') as $locale => $title)
        {
            $locale = new Localization(['locale' => $locale, 'title' => $title]);
            $locale = $item->localization()->save($locale);
        }

这很好用,但更新这种关系的最佳做法是什么?目前我正在尝试使用 Form::model 绑定。

@foreach($locales as $key => $locale)
{{ Form::text('title['.$locale.']', $model->translate($locale)->title, ['class' => 'form-control']) }}
@endforeach

我不知道 Input::old 在这种情况下如何工作,所以现在我使用 $model->translate($locale)->title 来获取正确的值。基本上 更新/验证 部分并没有真正起作用。您可以建议更改哪些内容以验证这种关系并进行更新?

【问题讨论】:

    标签: laravel laravel-4


    【解决方案1】:

    今天我找到了一个有效的解决方案来存储/更新与验证的关系。我希望这是最好/最简单的方法。我创建了一个带有验证输入的新数组,并相应地更改了视图错误。

    这是我的更新控制器。

    public function update($id)
    {
        // Find resource
        $item = Category::find($id);
    
        foreach(Input::get('title') as $locale => $title)
        {
            $v['title_'.$locale] = $title;
        }
    
        // Attempt validation
        if($item->validate($v))
        {
            foreach(Input::get('title') as $locale => $title)
            {
                $localization = $item->translate($locale);
                $localization->title = $title;
                $localization->save();
            }
    
            return Redirect::action('AdminCategoryController@edit', [$item->id]);
        }
        else
        {
            // Failure, get errors
            $errors = $item->errors();
    
            return Redirect::back()
                ->withInput()
                ->with('errors', $errors);
        } 
    }
    

    这是更新视图;

    {{ Form::model($model, ['action' => ['AdminCategoryController@update', $model->id], 'method' => 'PUT']) }}
        @foreach($locales as $key => $locale)   
            <div id="{{ $locale }}">
                <div class="form-group">
                    {{ Form::label('title['.$locale.']', _('admin.title_'.$locale)) }}
                    {{ Form::text('title['.$locale.']', $model->translate($locale)->title, ['class' => 'form-control']) }}
                    @if($errors->has('title_'.$locale))
                        <div class="help-block alert alert-danger">{{ $errors->first('title_'.$locale) }}</div>
                    @endif
                </div>
            </div>
        @endforeach
    {{ Form::close() }}
    

    这样你可以轻松地 CRUD,验证 Laravel 中所有类型的关系(输入数组)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-09-30
      • 1970-01-01
      • 2019-10-01
      • 2014-12-30
      • 2019-03-04
      • 1970-01-01
      相关资源
      最近更新 更多