Laravel Eloquent - Update() function always return true - laravel

Consider the code
return User::find($user_id)->update($data_array)?true:false;
if $data_array have some columns that are not present in User related table.
then also above statement return true.
e.g: $data_array=['not_in_the_table'=>'value'];
return User::find($user_id)->update($data_array)?true:false;
returns true. What is the condition when update returns 0 i.e. false?

If you use where('id','=',$user_id) like below instead of find($id), you will get error like Column not found for the columns that are not present in User related table. So it is best way to do this :
User::where('id','=',$user_id)->update(['column_name'=>'value']);
Instead of :
User::find($user_id)->update($data_array)?true:false;
Update method always return int. For more info Check Here
or If you want to update the the record by using Object Relation Mapping way then you can do like this :
$user = User::find($user_id) ;
$user->column_name = 'value';
if($user->save()){
//do something when user is update
}else{
// do something wehn user is not update
}

You cannot get error into false there because validation of Laravel use library.
For Laravel 4.2
public function update($user_id) {
$data_array = Input::all();
$validator = Validator::make(
$data_array,
array('name' => 'required|min:5')
);
if ($validator->passes()) {
// success as true
User::find($user_id)->update($data_array)
} else {
//failed as false
}
}
For more information about validator
I hope this help you

Related

How to add validate data search

I am using laravel for this project, i'm newbie at laravel then i want to add validate data if there is true then go to pdf blade, unless the data is false or wrong (i don't know what is it call so i named it True and False, but i hope you understand what i mean)
there is code in controller method search pdf
$id = $request->id;
$date = $request->date;
$pegawai = DB::table('pegawais')
->where('id', $id)
->whereDate('date', $date)
->get();
$pdf = PDF::loadview('pegawai_pdf', [
'pegawai'=>$pegawai
]);
return $pdf->stream();
and this is the output blade when i searched the data is true or exist
here
and this is the output blade when i searched but the data is false or not found data exist
here
fyi the data are fake data from seeder,
From your example, I will assume that you want to check if there is a result or not in $pegawai right? Then just count it.
if (count($pegawai) > 0) {
// show your pdf output here
} else {
// there is no data, do something here
}
to check this does not need to be a true false variable you can check this like this
if($pegawai){
$pdf = PDF::loadview('pegawai_pdf', [
'pegawai'=>$pegawai
]);
return $pdf->stream();
}else{
//show error here
}

difference between fill() and update() in laravel

I want to change value in table using ajax in laravel.
But when i use fill(), returning value is "success", but when i use update(), returning value is fail.
My source code is follow.
public function deleteCourse($id){
$test = Course::find($id)->fill(['is_deleted' => 1])->save();
$res = ['res' => 'success'];
return json_encode($res);
}
public function deleteCourse($id){
$test = Course::find($id)->update(['is_deleted'=>1])->save()'
$res = ['res'=>'success'];
return json_encode($res);
}
You can't call ->save() after ->update(), since it returns a boolean 1 or 0 (success or fail). The record is directly updated in the database, so ->save() is not required.
fill() on the other hand doesn't persist anything to the database until you call ->save(), so it is required in that instance.
public function deleteCourse($id){
$test = Course::find($id)->fill(['is_deleted' => 1])->save();
$res = ['res' => 'success'];
return json_encode($res);
}
// OR
public function deleteCourse($id){
$test = Course::find($id)->update(['is_deleted'=>1]);
$res = ['res'=>'success'];
return json_encode($res);
}
Fill will not save into database until you call ->save on the object.
Update will change the value in the database immediately.
In your case line was not terminated correctly. Add a semicolon at the end.
$test = Course::find($id)->update(['is_deleted'=>1]);

How to check data exists in the database

I have a function to add new property. But i want to check for duplicate data at column "code" before add new data into database. If data exists will appear a message error.
function addPro(Request $req)
{
$id = $req->type_id;
$type = AssetType::find($id);
if($req->save == 'save'){
$pro = new TypeProperties;
$pro->name = $req->name;
$pro->code = $req->code;
$pro->type = $req->type;
$pro->assettype_id = $req->type_id;
$pro->save();
Schema::table($type->code, function ($table) use ($pro) {
if ($pro->type == "textbox")
$table->string($pro->code )->nullable();
if ($pro->type == "textarea")
$table->text($pro->code )->nullable();
});
return redirect(url($type->id.'/add/property'))->with('message','Save successful');
}
return redirect(url('asset/type/'.$type->id));
}
You can use laravel Request Validation
function addPro(Request $req)
{
$id = $req->type_id;
$type = AssetType::find($id);
if($req->save == 'save'){
$req->validate([
'code' => 'required|unique:tablename'
]);
$pro = new TypeProperties;
$pro->name = $req->name;
$pro->code = $req->code;
$pro->type = $req->type;
$pro->assettype_id = $req->type_id;
$pro->save();
Schema::table($type->code, function ($table) use ($pro) {
if ($pro->type == "textbox")
$table->string($pro->code )->nullable();
if ($pro->type == "textarea")
$table->text($pro->code )->nullable();
});
return redirect(url($type->id.'/add/property'))->with('message','Save successful');
}
return redirect(url('asset/type/'.$type->id));
}
The most simple way to do this is by checking if code is_null :
if (is_null($pro->code)) {
// It does not exist
} else {
// It exists
}
The other way is to make a validation using Laravel's built in ValidateRequest class. The most simple use-case for this validation, is to call it directly in your store() method like this:
$this->validate($req, [
'code' => 'required|unique,
//... and so on
], $this->messages);
With this, you're validating users $req by saying that specified columns are required and that they need to be unique, in order for validation to pass. In your controller, you can also create messages function to display error messages, if the condition isn't met:
private $messages = [
'code.required' => 'Code is required',
'code.unique' => 'Code already exists',
//... and so on
];
You can also achieve this by creating a new custom validation class:
php artisan make:request StorePro
The generated class will be placed in the app/Http/Requests directory. Now, you can add a few validation rules to the rules method:
public function rules()
{
return [
'code' => 'required|unique,
//... and so on
];
}
All you need to do now is type-hint the request on your controller method. The incoming form request is validated before the controller method is called, meaning you do not need to clutter your controller with any validation logic:
public function store(StorePro $req)
{
// The incoming request is valid...
// Retrieve the validated input data...
$validated = $req->validated();
}
If you have any additional question about this, feel free to ask. Source: Laravel official documentation.
What does your migration look like for AssetType?
I ask because you can do this in the schema with ->unique() added to the column on the creation or make a migration to add the constraint.
You can also check with something like this:
// Search database table for entry
$entry = AssetType::where('code', '=', $pro->code)->first();
// If not found
if ($entry === null) {
// Save method here.
}
Otherwise, you can use the manual validator or create a Request with validation
References:
https://laravel.com/docs/5.8/queries#where-clauses
https://laravel.com/docs/5.8/validation#creating-form-requests
https://laravel.com/docs/5.8/validation#manually-creating-validators

One-shot laravel validator

I have a form where someone searches for something. Based on this form, I validate if the input is correct:
$validator = Validator::make(Input::all() , array(
'address' =>'required',
));
if($validator->fails()) {
return Redirect::to('/')->withErrors($validator);
}
After this, I want to validate something else (that a result object isn't empty), which is completely unrelated to the search. In other words, it's NOT input from a form.
1) Do I create another validator to validate this? Or
2) Is there a better way to simply check this value and spawn an object that can be returned with "withErrors"?
UPDATE
This isn't working for me:
$validator = Validator::make(
array(
'searches' => sizeof($search)
) ,
array(
'searches' => 'required|min:1'
)
);
if($validator->fails()) {
return Redirect::to('/')->withErrors($validator);
}
It's not working because for some reason it's picking up that the "searches" item should only be validated "sometimes"
you have two ways. one is custom validator
or there is a simpler way,
suppose,
private function foo()
{
$data = ''; //retrieved the data error here with whatever call you want to make
return !empty($data) ? true : false;
}
in the controller,
public function bar()
{
if(!$this->foo())
{
$messages = new \Illuminate\Support\MessageBag;
// you should use interface here. i directly made the object call for the sake of simplicity.
$messages->add('custom', 'custom error');
return Redirect::back()->withErrors($messages)->withInput();
}
}
in the view:
#if($errors->has('custom'))
<p>custom error output.</p>
#endif
it is just the outline to give you the idea.

How to check if the record exist using codeigniter

I'm creating a registration form using codeigniter. I understand that there is a validation for each field in CI but what I want to do is to validate a multiple field exist.
SELECT emp_id FROM emp_record WHERE firstname = 'firstname' AND lastname = 'firstname' AND birthdate = 'firstname'
If the query above find a match I want to alert on my view page that the record already exist.
Please help.
Appreciate it. Thanks.
Declare a custom callback function
function _check_firstname()
{
$firstname = $this->security->xss_clean($this->input->post('firstname'));
$array = array('firstname' => $firstname, 'birthdate' => $firstname);
$result = $this->db->select('emp_id')->from('emp_record')->where($array)->get();
if($result->num_rows())
{
$this->form_validation->set_message('_check_firstname', 'Record already exists');
return false;
}else
{
return true;
}
}
Set rules including (callback__check_firstname)
$this->form_validation->set_rules('firstname', 'First Name', 'trim|required|callback__check_firstname');
Now, when you'll check validation like
if ($this->form_validation->run()){
// passes
}
else{
// not passes, so show the view again
}
In the view, if you have something like this
<?php echo form_error('firstname') ?>
This will show the error message set in the custom callback function.
You could use num_rows() to do such things.
By using active record you can achieve this by doing the following
$qry = $this->db->select('emp_id')->from('emp_record')
->where('firstname', $firstname)
->where('lastname', $lastname)
->where('birthdate', $birthdate)
->get();
if ($qry->num_rows() > 0)
return TRUE;
else
return FALSE;
This will return TRUE if it finds at least one row in your database or FALSE if it finds nothing.
some people can/may have the same firstname,lastname and birthdate
But still if you want to have it that way you could create a callback validation
here is a snippet.
public function checkinput()
{
// you may want to sanitize the input
$data['fname'] = $this->input->post('fname');
$data['lname'] = $this->input->post('fname');
$data['mname'] = $this->input->post('fname');
//your model for checking data must return TRUE or FALSE
if($this->model->method_for_checking($data))
{
this->form_validation->set_message('checkinput', 'Duplicate data exists.');
return TRUE;
}else{
return FALSE;
}
}
Now you can use it on your validation rules i.e
$this->form_validation('fname','fname',callback_checkinput);
Other options are
Extend a form validation and create a validation rule there as not
to clutter the controller
Or ,After Submitting the form before inserting the data, you can check whether it is a duplicate and do the logical things their.

Resources