vendredi 2 octobre 2015

Laravel 5 form model binding with hasMany

I have two models: Category and CategoryValue.

Inside my Category model I have:

public function values()
{
    return $this->hasMany('App\CategoryValue');
}

Inside my CategoryValue I have:

function category()
{
    return $this->belongsTo('App\Category');
}

In my edit view, I have my form model binding like so:

{!! Form::model($category, ['route' => ['category.update', $category->slug], 'method' => 'PATCH']) !!}
    @include('partials.categoryForm')
{!! Form::close() !!}

Where $category is a chosen Category Model.

The categoryForm partial looks like:

<div class="form-group {{ $errors->has('name') ? 'has-error' : '' }}">
    {!! Form::label('name', 'Name') !!}
    {!! Form::text('name', null, ['class' => 'form-control']) !!}
    {!! $errors->first('name', '<span class="help-block">:message</span>') !!}
</div>

<div class="form-group {{ $errors->has('slug') ? 'has-error' : '' }}">
    {!! Form::label('slug', 'Slug') !!}
    {!! Form::text('slug', null, ['class' => 'form-control']) !!}
    {!! $errors->first('slug', '<span class="help-block">:message</span>') !!}
</div>

<div class="form-group">
    {!! Form::submit('Save Page', ['class' => 'btn btn-primary']) !!}
</div>

That's all working, but when editing the Category, I'd like to be able to edit (add/remove) associate CategoryValues. To start, I want the items returned from $category->values to be inside a textarea with each CategoryValue on a new line.

I can think of a couple of ways to do this: use a @foreach and generate the textarea, or popular a variable and use that in the binding. I'm not sure which of these, if either, is the "Laravel" way to do it. I'm also not sure if either of those can be used to update the records in the DB properly. How should this be done?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire