2013-09-24 49 views
0

我有一個模型類別。類別有很多本地化。當我店鋪分類,我有這方面的投入:HasMany關係舊輸入

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

其中我喜歡這家店在我CONTROLER:

 // 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 

我不知道如何輸入::老能在這種情況下工作,所以現在我使用$模型 - >翻譯($區域) - >標題,以獲得正確的值。基本上更新/驗證部分實際上並不工作。你可以建議改變以驗證這種關係並更新它?

回答

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('[email protected]', [$item->id]); 
    } 
    else 
    { 
     // Failure, get errors 
     $errors = $item->errors(); 

     return Redirect::back() 
      ->withInput() 
      ->with('errors', $errors); 
    } 
} 

這是更新視圖;

{{ Form::model($model, ['action' => ['[email protected]', $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。