Laravel 5.1 form model binding a one to many relationship

876 Views Asked by At

Is it possible to form model bind a one to many relationship when using arrays ?

In the example below I have one to many relation between the jobs and questions table.

A job can have many or no questions associated with it. In my blade template I want to know if it's possible to bind this relationship as I've been able to do so with the job industries relationship using a simple method on the job class getIndustryListAttribute(). I tried using the getQuestionListAttribute() method but it doesn't work ?

Tables:

 jobs
`id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
`job_title` VARCHAR(100) NOT NULL,

questions
`job_id` INT(10) UNSIGNED NOT NULL,
`question_id` INT(10) UNSIGNED NOT NULL,
`question_text` VARCHAR(150) NOT NULL,
`expected_answer` TINYINT(1) NOT NULL,
    PRIMARY KEY (`job_id`, `question_id`),

Models:

class Job extends Model {

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

    public function industries()
    {
        return $this->belongsToMany('App\Industry', 'job_industry');
    }

    public function getIndustryListAttribute()
    {
        return $this->industries->lists('id')->all();
    }

    public function getQuestionListAttribute()
    {
        return $this->questions->lists('question_text', 'question_id')->all();
    }

}

class Question extends Model {
    public function job()
    {
        return $this->belongsTo('App\Job');
    }
}

Form:

   @for ($i = 0; $i < 5; $i++)
       <div class="form-group >
          {!! Form::label("question_list.{$i}.question_text", 'Question', ['class' => '']) !!}
          {!! Form::text("question_list[{$i}][question_text]", null, ['maxlength' => '150', 'class' => 'form-control']) !!}
       </div>
       <div class="form-group">
          {!! Form::label("question_list.{$i}.expected_answer", 'Expected answer', ['class' => '']) !!}
          {!! Form::select("question_list[{$i}][expected_answer]", ['' => 'Please Select', 'true' => 'Yes', 'false' => 'No'], null, ['class' => 'form-control']) !!}
      </div>
    @endfor

     <div class="form-group">
         {!! Form::label('industry_list', 'Industry', ['class' => '']) !!}
         {!! Form::select('industry_list[]', $industries, null, ['id' => 'industry_list', 'class' => 'form-control', 'multiple']) !!}
     </div>

Note: the question_id is simply the array index value.

1

There are 1 best solutions below

0
On

You can bind one to many relationship by using Form Model Accessors

class Job extends Model 
{
    use \Collective\Html\Eloquent\FormAccessible;

    public function formQuestionAttribute($value)
    {
        // This will return array, You want to implode it if you expect string.
        return $this->questions;
    }
}

In your blade file:

{!! Form::text('questions') !!}

See LaravelCollective for more information.