Ad

Laravel Many To May Relationship

- 1 answer

I have two tables passport and status and a pivot table passport_statuses.I have enter passport details and select status from dropdown but I am unable to save data in pivot table.please help.My codes are as below:

Passport model

class Passport extends Model
{
protected $fillable=[
'Full_Name',
'Date_of_Birth',
'Passport_Number',
'comments',
'Delivered_to_owner'
];
public function status()
{
return $this->belongsToMany('App\Statuses',"passport_statuses","passport_id","statuses_id")->withTimestamps();
    }
}

Statuses model

class Statuses extends Model
{
 protected $fillable=[
'Status_Name'
];
public function passport()
{
return $this->belongsToMany('App\Passport',"passport_statuses","passport_id","statuses_id")->withTimestamps();
}
}

PassportController

public function create()
{
        $statuses=Statuses::lists('Status_Name','id');
    return view('admin.passport.create')->with('statuses',$statuses);
}
 public function store(Request $request)
{
$passport=Passport::create($request->all());
$passport->status()->attach($request->input('statuses'));
  return redirect('admin/passport');
}

View

{!!Form::open(['url'=>'admin/passport'])!!}
<div class="form-goup">
{!!Form::label('Full_Name','Full Name')!!}
{!!Form::text('Full_Name',null,['class'=>'form-control'])!!}
</div>
<div class="form-goup">
{!!Form::label('Date_of_Birth','Date of Birth')!!}
{!! Form::input('date', 'Date_of_Birth', null, ['class' => 'form-control', 'placeholder' => 'Date']) !!}
</div>
{!!Form::label('Passport_Number','Passport Number')!!}
{!!Form::text('Passport_Number',null,['class'=>'form-control'])!!}
<div class="form-goup">
{!!Form::label('Status_Name','Status')!!}
{!!Form::select('Status_Name',$statuses,null,['class'=>'form-control'])!!}
</div>

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

</div>
{!!Form::close()!!}
Ad

Answer

I was able to solve this by changing input('statuses') to input('Status_Name') in PassportController

$passport->status()->attach($request->input('Status_Name'));
Ad
source: stackoverflow.com
Ad