Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validation check (if 1 equal to some value from database) Laravel 5

Is there any way in Laravel 5 to check if some value equal with value from database?

Here is what I try to do: I have table users and in table users I have additional column admin_id. In validation I need to check if admin_id form database equal to 1.

Here is my current code:

  $inputs = array(
        'projects' => Input::get('project'),
        'users'    => Input::get('workers')

    );

    $rules = array(
        'projects' => 'required',
        'users'    => 'required'
    );

    $validator = Validator::make($inputs,$rules);
    if($validator->fails()){
        return false;            
       }else{
        return true; 
    }
like image 632
Vladimir Djukic Avatar asked Mar 21 '15 13:03

Vladimir Djukic


1 Answers

I don't know what is users input here - is it if from users table? If yes, you can then create your rules this way:

$rules = array(
        'projects' => 'required',
        'users'    => ['required', 'exists:users,id,admin_id,1']
    );

So now it will be verified if users matches user_id from users table where admin_id equals 1.

You should also consider Laravel 5 Requests objects to validate input. It's much more clean than putting code in Controller/Model/Repository. More about Requst Validation.

like image 122
Marcin Nabiałek Avatar answered Sep 27 '22 21:09

Marcin Nabiałek