简体   繁体   中英

how to validate data insert to table in Laravel 5.2

I am using addpermission function to save values in to permission table.

public function addPermission(Request $request, $id,  Permission $permission)
{
     $this->validate($request, [
        'status'   => 'required'
    ]);

    $permission = new Permission;

    $permission->status = $request->input('status');
    $permission->project_id       = $id;
    $permission->collaborator_id =  $request->input('cid');
    $permission->save();
    return redirect()->back()->with(
        'info',
        'Permission has been added to your Collaborator successfully'
    );
}

this is My permiisionadd form action

<form class="form-vertical" role="form" method="post"
    action="{{ route('projects.collaborators.permission', $project->id,$collaborator->id) }}">

    <input type="hidden" id="cid" name="cid" value="{{ $collaborator->user()->first()->id }}" />
    <div class="form-group{{ $errors->has('status') ? ' has-error' : '' }}">
    <label for="status" class="control-label">Choose Permission</label>
    <select name="status" id="status">
    <option value="">Choose a status</option>
    <option value="3">View Only</option>
    <option value="2">Edit Tasks</option>
    <option value="1">Admin</option>
    </select>
    @if ($errors->has('status'))
    <span class="help-block">{{ $errors->first('status') }}</span>
    @endif
    </div>
      <div class="form-group">
        <button type="submit" class="btn btn-default">Create</button>
      </div>
      <input type="hidden" name="_token" value="{{ csrf_token() }}"> 

now I need to validate this form if some user add new value to the existing row (generate some message)

how can I do this?

If I understood you correctly, you may have to use the unique validation rule on your hidden cid field, like this:

     $this->validate($request, [
        'cid'      => 'unique:permissions,collaborator_id',
        'status'   => 'required'
    ]);

This way if this user has already a row in the table, it won't let him create a new one and a validation error will be displayed.

However may have to create a custom error message for this, to help the user understand why his form is not accepted. Also dont forget to create an extra span somewhere on your form for the errors of the cid field to appear:

@if ($errors->has('cid'))
   <span class="help-block">{{ $errors->first('cid') }}</span>
@endif

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM