Boolean Values Not Saved, Laravel - mysql

I have some boolean fields sent with a POST request to a Laravel controller. However, every data in the request is saved except the booleans.
Model Fillables:
protected $fillable = [
'name',
'code',
'governorate',
'point',
'overnight',
'isResort',
'family',
'youth',
'status',
'description',
'user_id',
'price_currency',
'map',
'checkoutMessage',
'checkoutYoutubeVideo',
'max_person_count',
'more_person_price',
'age_limit',
'productYoutubeVideo',
'resortProductCount',
];
Controller
public function store(Request $request)
{
try{
$data = $request->all();
$data['user_id'] = auth('user-api')->user()->id;
$gev_id = Str::before($request->governorate_id, ',');
$product = RentProduct::create($data);
$product->update([
'code' => $gev_id.rand((int)0, (int)pow(2, 256)).$product->id,
]);
return $this->returnData("product", RentProduct::where('id', $product->id)->with('photos')->get());
}catch(\Throwable $th){
return $this->returnError($th->getCode() , $th->getMessage());
}
}
The strange problem is, when I die & dump the created product from store method, boolean appears in the right nature but it saved without that booleans.
Postman request

Don't send 'true' as a string, send 1 (true) or 0 (false) as a int. By the way don't forget to change your column type to tinyint(1) data type.

Related

can't update json column using Laravel eloquent model

I'm trying to test an update to an Eloquent model...
/** #test */
public function updates_to_json_fields_are_logged()
{
$data = json_encode(["json_key" => "old_value"]);
$individual = Individual::factory()->create([
"information" => $data
]);
json_decode($individual->information)->json_key = "new_value";
$individual->save();
echo(var_dump($individual));
$this->assertTrue(false);
}
information is a json column.
When I log $individual after saving it, the value of "information->json_key" is still "old_value". Can anyone tell me why?
To change the $individual object without fancy assign
/** #test */
public function updates_to_json_fields_are_logged()
{
$data = json_encode(["json_key" => "old_value"]);
$individual = Individual::factory()->create([
"information" => $data
]);
$decodedInformation = json_decode($individual->information);
$decodedInformation->json_key = "new_value";
$individual->information = json_encode($decodedInformation);
$individual->save();
echo(var_dump($individual));
$this->assertTrue(false);
}
You don't change original $individual object, but the result of json_decode().

Eloquent Accessor: update attribute on model instance

I want to decrypt the email attribute of my model:
protected $fillable = [
'email',
'password',
'remember_token',
'status',
'name',
'lastname',
'password_changed_at',
'role',
'attempts'
];
By using this mutator with JSON Append
protected $appends = ['email'];
public function getEmailAttribute($value)
{
return $this->attributes['email'] === Crypt::decrypt($value);
}
The problem I'm facing it's that when I execute a dump and die, the response hasn't change the email attribute.
Any ideas on how i can change the response to return the email decrypted?
Thanks :)
There is no need to use appends, try below:
public function getEmailAttribute($value)
{
return Crypt::decrypt($value);
}

checkbox data not insert in mysql using codeigniter

I try to insert my checkbox data in CodeIgniter. but data did not inserted in the database.
here is my view file:
<input type="checkbox" name="feature[]" value="WIFI" >
<input type="checkbox" name="feature[]" value="TV">
I am trying to use implode to convert the array into the string, but then I don't how to add in $data array, so they inserted in together
here is my controller:
public function save()
{
$this->load->model('Partner_model');
$feature = $this->input->post('feature');
$fea=array(
'feature'=>json_encode(implode(",",$feature))
);
$user_data= array(
'pname' => $this->input->post('pname'),
'type' => $this->input->post('type'),
'address' => $this->input->post('address'),
'about' => $this->input->post('about'),
'city' => $this->input->post('city'),
'code' => $this->input->post('code')
);
if($this->Partner_model->save($user_data,$fea))
{
$msg = "save sucesss" ;
}
else
{
$msg = "not save";
}
$this->session->set_flashdata('msg', $msg);
$this->load->view('partner_profile');
}
& here is my model:
public function save($data,$fea)
{
return $this->db->insert('property', $data,$fea);
}
Your model is faulty.
You are passing three arguments to insert() but the third you use is not appropriate.
That argument should be a boolean that indicates whether to escape values and identifiers or not. You need to incorporate $fea into $data which should probably be done in the controller.
There is an easier way to create the array $user_data since it is essentially a copy of $_POST just use $this->input->post().
Also, there is no obvious reason why you use json_encode. Unless you need it that way when you retrieve it from the DB there is no reason to bother with it. Consider removing json_encode.
First, change the model
public function save($data)
{
return $this->db->insert('property', $data);
}
Here's a revised save method
public function save()
{
$this->load->model('Partner_model');
$user_data = $this->input->post(); //makes a copy of $_POST
$feature = $this->input->post('feature');
if($feature) //because $feature will be null if no boxes are checked
{
$user_data['feature'] = json_encode(implode(",", $feature));
}
$msg = $this->Partner_model->save($user_data) ? "save sucesss" : "not save";
$this->session->set_flashdata('msg', $msg);
$this->load->view('partner_profile');
}
An explanation as requested via comments.
A call to $this->input->post('pname') returns the value of $_POST['pname'] if it is exists, but returns null if it does not exist.
When you create $user_data you make six calls to $this->input() with a different "key" each time to make a copy of $_POST.
$this->input->post() without any arguments returns the whole $_POST array. (See documentation)
$user_data = $this->input->post();
Makes a copy of $_POST using one line of code. It will include $_POST['feature'] if any boxes are checked, but $_POST['feature'] will not be set if no boxes are checked.
There are two ways to test if any boxes were checked. First we can test if isset($_POST['feature']) == true or we can test if $this->input->post('feature') == true. I use the second with the call
if($feature)
Which is pretty much the same as any of the following lines
if($feature != false)...
if($feature != null)...
if( ! empty($feature))...
if( ! is_null($feature))...
In other words, if($feature) evaluates as true if $feature is set and is anything except null, false, 0, "0", "" (an empty string), array() (an empty array)
public function save()
{
$this->load->model('Partner_model');
$feature = $this->input->post('feature');
$user_data= array(
'pname' => $this->input->post('pname'),
'type' => $this->input->post('type'),
'address' => $this->input->post('address'),
'about' => $this->input->post('about'),
'city' => $this->input->post('city'),
'code' => $this->input->post('code'),
'feature'=>json_encode(implode(",",$feature))
);
if($this->Partner_model->save($user_data)){
$msg = "save sucesss" ;
}else{
$msg = "not save";
}
$this->session->set_flashdata('msg', $msg);
$this->load->view('partner_profile');
}
model file should be :
public function save($data) {
return $this->db->insert('property', $data);
}

Add new attribute dynamically to the existing model object in Yii2 framework

In Yii2 framework is it possible to add a new attribute dynamically to an existing object, which is retrieved from Database?
Example
//Retrieve from $result
$result = Result::findone(1);
//Add dynamic attribute to the object say 'result'
$result->attributes = array('attempt' => 1);
If it is not possible, please suggest an alternate best method to implement it.
Finally I would be converting the result to a json object. In my application, at the behaviour code block, I have used like this:
'formats' => [
'application/json' => Response::FORMAT_JSON,
],
You can add define a public variable inside your model, that will store dynamic attributes as associative array. It'll look something like this:
class Result extends \yii\db\ActiveRecord implements Arrayable
{
public $dynamic;
// Implementation of Arrayable fields() method, for JSON
public function fields()
{
return [
'id' => 'id',
'created_at' => 'created_at',
// other attributes...
'dynamic' => 'dynamic',
];
}
...
..in your action pass some dynamic values to your model, and return everything as JSON:
public function actionJson()
{
\Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
$model = Result::findOne(1);
$model->dynamic = [
'field1' => 'value1',
'field2' => 2,
'field3' => 3.33,
];
return $model;
}
In result you will get JSON like this:
{"id":1,"created_at":1499497557,"dynamic":{"field1":"value1","field2":2,"field3":3.33}}

API Json in symfony form

i'm creating an application in symfony 2.8 (with php5.4) and in my form (that i'm building) i want to display a list of a projects through an API in json format.
Now i'm stuck, and i don't know how to do this.
I know the database of the API there is a table "projects" and i want target the column 'name' to display names of projects
here's my code:
/**
* #Route("/form")
*/
public function formAction(Request $request)
{
$url = 'https://website.com/projects.json';
$get_json = file_get_contents($url);
$json = json_decode($get_json);
$form = $this->createFormBuilder()
->add('Project', 'choice') // <-- ???
->add('send', 'submit' ,array('label' => 'Envoyer'))
->getForm();
$form->handleRequest($request);
return $this->render('StatBundle:Default:form.html.twig', array('form' => $form->createView(), 'project' => $json));
}
You can pass the choice as second argument as array as example:
$jsonAsArray = json_decode($get_json, true); // with true return an array
$builder->add('Project', 'choice', array(
'choices' => $jsonAsArray,
// *this line is important, depends of the data*
'choices_as_values' => false,
));
More info in the doc here.
Hope this help