I was doing great so far until I ran into another problem with validation. I'm trying to update a user related table called socialLinks. The problem is every time I update, since it's a model backed form, the prefilled values in the form gets pass through validations and I get a 'has already been taken' error in return.
After doing a bunch of googling, I tried to pass userId through update, but i haven't had any success. I had this problem before but I was validating a column from User. Now I'm trying to validate a column from another table with a relationship with user and nothing I tried before works. Super Frustrating.
my form
{!! Form::model($user_links,['method' => 'PATCH', 'action'=> ['UserController@update_social']]) !!}
<div class='row form-group'>
<div class='col-md-2'>
{!! Form::label('facebook', 'Facebook Username') !!}
</div>
<div class='col-md-7'>
{!! Form::text('facebook', null,['class'=>'form-control']) !!}
</div>
</div>
<div class='row form-group'>
<div class='col-md-2'>
{!! Form::label('twitter', 'Twitter Username') !!}
</div>
<div class='col-md-7'>
{!! Form::text('twitter', null,['class'=>'form-control']) !!}
</div>
</div>
<div class='row form-group'>
<div class='col-md-2'>
{!! Form::label('reddit', 'Reddit Username') !!}
</div>
<div class='col-md-7'>
{!! Form::text('reddit', null,['class'=>'form-control']) !!}
</div>
</div>
<div class='row form-group'>
<div class='col-md-3'>
{!! Form::submit('Save Changes',['class'=>'btn btn-md btn-success']) !!}
{!! Form::close() !!}
routes
Route::get('/account/social','UserController@social');
Route::patch('/account/social','UserController@update_social');
and controllers
public function social(Request $request){
$user = $request->user();
$user_links= $request->user()->links;
return view('user.edit.social_connect',compact('user_links','user'));
}
public function update_social(Request $request){
$user = $request->user();
$validator=Validator::make($request->all(),[
'facebook' => 'unique:social_links,facebook,'.$user->id,
'twitter' => 'unique:social_links,twitter'.$user->id,
'reddit' => 'unique:social_links,reddit,'.$user->id,
'google' => 'unique:social_links,google,'.$user->id
]);
if ($validator->fails()){
var_dump($user->id);exit;
return Redirect::back()->withErrors($validator)->withInput();
}
$data=Input::all();
$links = $user->links;
if ($links == null){
$links = new SocialLinks();
$links->fill($data);
$links->user_id=$user->id;
$links->save();
}else{
$links->fill($data);
$links->save();
}
return Redirect::back()->with('message','Your profile has been updated');
}
Update put validation logic in controller