Validation check (if 1 equals some value from the database) Laravel 5

Is there a way in Laravel 5 to check if the value is equal to the value from the database?

Here is what I am trying to do: I have a users table, and users of the table I have an additional admin_id column. When checking, I need to check if the database form admin_id is 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; } 
+5
source share
3 answers

I do not know what to enter users here - is it from the users table? If so, you can create your own rules as follows:

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

So now this will be checked if users matches the user_id table from users , where admin_id is 1 .

You should also consider Laravel 5 Requests for objects to validate input. This is much cleaner than putting code in a controller / model / repository. Learn more about Requst Validation .

+3
source

$rules = array( 'users' => 'exists:users,admin_id' ); where is the name of the user table. You can see that you also want to use users as the name of the form field

0
source
  $rules = array( 'projects' => 'required', 'users' => [ 'required', Rule::exists('users', 'id')->where(function ($query) { $query->where('admin_id', 1); }), ], ); 

Or, if admin_id is dynamic, use:

  $variable = 1; $rules = array( 'projects' => 'required', 'users' => [ 'required', Rule::exists('users', 'id')->where(function ($query) use ($variable) { $query->where('admin_id', $variable); }), ], ); 
0
source

Source: https://habr.com/ru/post/1215815/


All Articles