Validate two column exists in a row Laravel - laravel-5.4

How to validate two column exists in a row by #Laravel 5.4
Now am doing this like below way :
My Controller Code :
$validator = \Validator::make($request->all(), [
'classlevel_id'=>'required',
'book_name'=>'required|string',
'class_no'=>'required|integer',
]);
if($validator->fails())
{
return response()->json(['errors'=>$validator->errors()->all()]);
}else{
$valid = DB::table('books')->where('class_no',$request->class_no)->where('book_name',$request->book_name)->exists();
if($valid){
return response()->json(['warning'=>"Book : ".$request->book_name." and class : ".$request->class_no." already Exists"]);
}
}
i also tried to do validate like below way :
$validator = \Validator::make($request->all(), [
'classlevel_id'=>'required',
'book_name'=>'required|string|unique:books|required_with:class_no',
'class_no'=>'required|string|unique:books|required_with:book_name',
]);
is there any Laravel Validate command for validate two columns exists in a row?

U have to use Laravel custom Validation rule
https://laravel.com/docs/5.6/validation#using-rule-objects

Related

Check if a field is empty while importing data from Excel file in Laravel?

I am trying to import data from excel file into database tables in Laravel. I have successfully imported the data but If I mistakenly leave a field empty then I get error that column cannot be null. So I need check if the all necessary data is provided.
I use this code.
IndependentContractor::create(['staff_id' => $staff->id, 'address' => $excel_row['address'], 'longitude' => $excel_row['longitude'], 'latitude' => $excel_row['latitude'], 'tax_id' => $excel_row['tax_id'], 'business_name' => $excel_row['business_name'], 'person_incharge' => $excel_row['person_incharge'], 'phone_of_person_incharge' => $excel_row['phone_of_person_incharge'], 'general_manager' => $excel_row['general_manager'], 'phone_of_general_manager' => $excel_row['phone_of_general_manager']]);
I can use If() to check the data but I will have to repeat this in almost 7 places because there are 7 different tables in which data is being stored.
also if statement will look like this.
if(!empty($excel_row['address']) && !empty($excel_row['longitude']) && !empty($excel_row['latitude']) && !empty($excel_row['business_name']) and so on )
So is there any better way to achieve this?
Thanks.
you can try using looping, using the array_key, assumming database column name = excel column name
example :
$data = [];
foreach($excel_row as $key => $value){
if(!empty($excel_row[$key])){
$data[$key] = $excel_row[$key];
}else{
dd('empty column found'); //your code here
}
}
//if everything goes fine
IndependentContractor::create($data);
class UsersImport implements ToModel, WithUpserts
{
/**
* #return string|array
*/
public function uniqueBy()
{
return 'email';
}
if (!isset($row[0])) {
return null;
}
return new User([
'name' => $row[0],
]);
}

Retrieve specific data using JSON decode Laravel

I'm new to Laravel. I need to retrieve specific data from the database using the JSON decode. I am currently using $casts to my model to handle the JSON encode and decode.
This is my insert query with json encode:
$request->validate([
'subject' => 'required|max:255',
'concern' => 'required'
]);
$issue = new Issue;
$issue->subject = $request->subject;
$issue->url = $request->url;
$issue->details = $request->concern;
$issue->created_by = $request->userid;
$issue->user_data = $request->user_data; //field that use json encode
$issue->status = 2; // 1 means draft
$issue->email = $request->email;
$issue->data = '';
$issue->save();
The user_data contains {"id":37,"first_name":"Brian","middle_name":"","last_name":"Belen","email":"arcega52#gmail.com","username":"BLB-Student1","avatar":"avatars\/20170623133042-49.png"}
This is my output:
{{$issue->user_data}}
What I need to retrieve is only the first_name, middle_name, and last_name. How am I supposed to achieve that? Thank you in ADVANCE!!!!!
As per the above code shown by you it will only insert data into the database.For retrieving data you can make use of Query Builder as i have written below and also you can check the docs
$users = DB::table('name of table')->select('first_name', 'middle_name', 'last_name')->get();
I will recommend using Resources. It really very helpful laravel feature. Check it out. It is a reusable class. You call anywhere and anytime.
php artisan make:resource UserResource
Go to your the newly created class App/Http/Resources/UserResource.php and drfine the column you want to have in your response.
public function toArray($request) {
return [
"first_name" => $this->first_name,
"middle_name" => $this->middle_name,
"last_name" => $this->last_name
]
}
Now is your controller you can use the UserResource like folow:
public function index()
{
return UserResource::collection(User::all());
}
Or after inserting data you can return the newly added data(f_name, l_name...)
$user = new User;
$user->first_name= $request->first_name;
$user->middle_name= $request->middle_name;
$user->last_name= $request->last_name;
$user->save();
$user_data= new UserResource($user);
return $user_data;

How do I make the most effective and efficient logic to check the data in the database exist or not?

I use laravel 5.6
I have a json file containing 500 thousand records. I want to create a logic to check whether the id of each record already exists or not in the database. If it doesn't already exist, then there will be a data insert process. If it already exists, there will be a data update process
I have made logic. I just want to make sure whether my logic is effective or not
My logic code like this :
$path = storage_path('data.json');
$json = json_decode(file_get_contents($path), true);
foreach ($json['value'] as $value) {
$data = \DB::table('details')->where('id', '=', $value['Code'])->get();
if ($data->isEmpty()) {
\DB::table('details')->insert(
[
'id' => $value['Code'],
'number' => $value['Number'],
...
]
);
}
else {
\DB::table('details')
->where('id', '=', $value['Code'])
->update([
'id' => $value['Code'],
'number' => $value['Number'],
...
]);
}
}
The code is working. But the process seems really long
Do you have another solution that is better?
updateOrCreate
You may also come across situations where you want to update an existing model or create a new model if none exists. Laravel provides an updateOrCreate method to do this in one step. Like the firstOrCreate method, updateOrCreate persists the model, so there's no need to call save():
// If there's a flight from Oakland to San Diego, set the price to $99.
// If no matching model exists, create one.
$flight = App\Flight::updateOrCreate(
['departure' => 'Oakland', 'destination' => 'San Diego'],
['price' => 99]
);
in your case your code should be like this (create Details model first) :
$path = storage_path('data.json');
$json = json_decode(file_get_contents($path), true);
foreach ($json['value'] as $value) {
Details::updateOrCreate(
[ 'id' => $value['Code'] ],
[ 'number' => $value['Number'], ... ]
);
}
i think that's the best way to do it. Eloquent return's a collection so you cant just validate that your string is null.

How can i use a component inside a Cell?

I'm looking for a way to use component inside a cell, is there any way ?
I tried :
$this->loadComponent('SessionsActivity');
My Cell :
namespace App\View\Cell;
use Cake\Core\Configure;
use Cake\View\Cell;
class UserCell extends Cell
My query :
$user = $this->Users
->find()
->where([
'Users.id' => $this->request->id
])
->contain([
'Towns' => function ($q) {
return $q->find('short');
},
'Countries' => function ($q) {
return $q->find('short');
}
])
->map(function ($user) {
$user->online = $this->SessionsActivity->getOnlineStatus($user);
return $user;
})
->first();
Using the same example at the CakePHP cells documentation, suppose you want to show the inbox for the connected user. You'd want to access the Auth component to take the connected user id.
AFAIK, Cells act like view-controller, a view part display.ctp file, and a controller part where you access the model to generate data for the view.
I'm using CakePHP 3.0 and $this->_registry doesn't work.
You could try:
$this->SessionsActivity = $this->_registry->load('SessionsActivity');
it is another question if you should use a component here

How to add combined unique fields validator rule in Laravel 4

I am using Laravel 4.2 and mysql db . I have an exam table in which i am taking Exams entry and the fields are --> id | examdate | batch | chapter | totalmarks
I have made a combined unique key using $table->unique( array('examdate','batch','chapter') ); in schema builder.Now I want to add a validation rule to it. I know i can add unique validation by laravel unique validator rule but the problem is ,it checks only for one field . I want it to add uniqueness to the 3 fields combined(user must not be able to add second row with same value combination of examdate,batch and chapter fields).
Is it even possible to do it in laravel 4 .Is there any workaround if its not possible?
You could write a custom validator rule. The rule could look something like this:
'unique_multiple:table,field1,field2,field3,...,fieldN'
The code for that would look something like this:
Validator::extend('unique_multiple', function ($attribute, $value, $parameters)
{
// Get table name from first parameter
$table = array_shift($parameters);
// Build the query
$query = DB::table($table);
// Add the field conditions
foreach ($parameters as $i => $field)
$query->where($field, $value[$i]);
// Validation result will be false if any rows match the combination
return ($query->count() == 0);
});
You can use as many fields as you like for the condition, just make sure the value passed is an array containing the values of the fields in the same order as declared in the validation rule. So your validator code would look something like this:
$validator = Validator::make(
// Validator data goes here
array(
'unique_fields' => array('examdate_value', 'batch_value', 'chapter_value')
),
// Validator rules go here
array(
'unique_fields' => 'unique_multiple:exams,examdate,batch,chapter'
)
);
It didn't work for me so I adjusted the code a tiny bit.
Validator::extend('unique_multiple', function ($attribute, $value, $parameters, $validator)
{
// Get the other fields
$fields = $validator->getData();
// Get table name from first parameter
$table = array_shift($parameters);
// Build the query
$query = DB::table($table);
// Add the field conditions
foreach ($parameters as $i => $field) {
$query->where($field, $fields[$field]);
}
// Validation result will be false if any rows match the combination
return ($query->count() == 0);
});
The validator looks like this. You don't need a particular order of DB table column names as stated in the other answer.
$validator = Validator::make($request->all(), [
'attributeName' => 'unique_multiple:tableName,field[1],field[2],....,field[n]'
],[
'unique_multiple' => 'This combination already exists.'
]);