HasMany关系旧输入

时间:2013-09-24 13:39:09

标签: laravel laravel-4

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

{{ 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来获取正确的值。基本上更新/验证部分确实不起作用。您可以建议更改以验证此类关系并更新它?

1 个答案:

答案 0 :(得分:0)

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

这是我的更新控制器。

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() }}

通过这种方式,您可以轻松地在Laravel中验证所有类型的关系(输入数组)。

相关问题