How to save the json array data in database in laravel? - laravel

does anyone know how to store the data in this format ["123"] in PHPMyAdmin?
Now the data I store into the database is only the value which is 123. I want to store the data like this ["123"]. Does anyone know how to do this?
Here is my code:
Company::create([
'companyID' => $people->people_id,
]);

To store data the way you want to, you need to change the datatype for the column of the table to json. It can be done in your migration file like:
$table->json('column_name');
After migrating your table you have to add casting for the specific column in your model file. It can be done as:
protected $casts = [
'column_name' => 'array',
];
Once you have done this, you can then store data as json in your database.
You can find more information about casting at Laravel Docs here.
https://laravel.com/docs/8.x/eloquent-mutators#array-and-json-casting

You can save text data in mysql table column. For this you should change your column type to text and follow the following code as reference.
You will have to change your array to json data and pass variable to create method as value. Remember that, for storing string value you will have to wrap value with quotations.
$data = json_encode([
123, "124", 134.4, "450"
]);
Company::create([
'companyID' => $data
]);

Related

How do I "json_decode" a single column data after fetch from database in Laravel?

I am saving an array in one column of my database using json_encode as follows and it works:
$service->description = $request->service_description;
$service->image = json_encode($url);
$service->duration = $request->service_delivery_time;
When I fetch the data I get a string. I am fetching using $service = Service::findOrFail($id);. I can decode the individual column as done below and pass it to the view.
$service = Service::findOrFail($id);
$images = json_decode($service->image);
return view('services.show',['service'=>$service , 'images'=>$images]);
What I am asking is, can I decode the images in one query?
Well this is a single query, json_decode runs after the SQL query returned your desired result.
What you can do is add a $casts property to your Service model so Laravel encodes/decodes it automatically for you, then you don't need to store these values with json_encode, just do $service->image = $url, and when you run findOrFail, the image property will already be a decoded json.
protected $casts = [
'image' => 'array',
];
Here's the documentation
You can use $cast or Accessor
1: $cast:
protected $casts = [
'image' => 'array'];
2: Accessor:
public function getImageAttribute()
{
return json_decode($this->attributes['image']);
}

How to prevent duplication when I reload my page to insert csv file to the database in laravel

Data duplicates in the database when I reload the code using laravel
I have tried to use laravel methods like "updateOrInsert" or "updateOrCreate " to prevent csv data duplication but it does't work? Please help!!
Here is the section how to import csv data to database
public function importCsv()
{
$products = $this::parseCsv('data.csv');
var_dump($products);
if (!empty($products)) {
foreach($products as $product) {
Product::create($product);
}
}
DB::table('products')
->updateOrInsert(
['name' => 'Jonathan', 'job'=>'consult'],
['name' => 'Johana']
);
return $this->parseCsv('data.csv');
}
Csv data duplicates in the database
Laravel determines whether the record already exists in the database by attempting to find it using the id of the record, not by comparing the data.
Your CSV file needs to have an id field that matches in both the CSV record and the database record.

Prevent data from being submitted in a form

I have a HTML form in my Laravel Blade view, with a leaflet map inside to show some data. The problem is, when I want to submit my form, this map is generating data and inserting it into the form, with the field name: "leaflet-base-layers_xx" where xx are random numbers that change everytime, so I can't just unset this data in my controller.
$data = $request->all();
unset($data['leaflet-base-layers_95']);
Is there any way I could prevent the map from submitting data. Or any way I could unset the field I want, knowing that it has a flexible name ?
You should be validating the request. This will not only validate the fields that you do want, but will also provide an easy way filter out any fields that you don't want or weren't expecting to receive.
For example, if your form should only have a title and body field
$data = $request->validate([
'title' => 'required|unique:posts|max:255',
'body' => 'required',
]);
Now $data will now only contain 'title' and 'body', no matter what other fields were submitted.
If you take this a step further and use a Form Request you can use $request->validated() method which again will only contain the validated fields and none of the other garbage you don't want.
$data = $request->validated();
Aside from this solving your problem, as a matter of good practice you should always only ever work with validated data. Passing unvalidated data around your app is a recipe for disaster.
Refs: https://laravel.com/docs/5.8/validation

Yii2 only show data that has attached time less than current time

How do I can select data to show based on comparation in yii2 Activerecord? My data record from db contain column depTime. So I want to show only data that has depTime less than current time.
Here is my function in my controller.
public function actionSelectedTeam($id) {
$searchModel = new TeamSearch();
$dataProvider= $searchModel->search(Yii::$app->request->queryParams);
$dataProvider->pagination = [
'pageSize' => 5
];
return $this->render('team-info', [
'model' => $this->findModel($id),
'dataProvider' => $dataProvider,
]);
}
Or there is another way to do that? I mean outside this method, maybe from the model.
Thankyou.
You will always have the records displayed that are smaller than the current time, other than they are some kind of reservations and you are providing future date/time manually.
You haven't specified what is the type of the depTime column, I assume that you have a datetime column, you can use the time() and now() function to achieve this.
You can add the following line in your search model's search() method before you return the $dataProvider which is subtracting the depTime from the current time and if the result is positive it will include the record.
$query->andFilterWhere(['>', new Expression('time(now()) - time(depTime)'), 0]);

Return Eloquent model with different name from database tables

I want to return a JSON of an Eloquent model, but I'd like to change the array keys. By default they are set as the table field names, but I want to change them.
For example if I have a users table with two fields : id and user_name
When I return User::all(); I'll have a JSON with "[{"id" => 1, "user_name" => "bob}] etc.
I'd like to be able to change user_name to username. I haven't found the way to do it without an ugly foreach loop on the model.
I'm not sure why you would want to do this in the first place and would warn you first about the structure if your app/would it be better to make things uniform throughout.. but if you really want to do it.. you could do:
$user = User::find($id);
return Response::json(array('id' => $user->id, 'username' => $user->user_name));
That will return a JSON object with what you want.
You can also change the name of the key with:
$arr[$newkey] = $arr[$oldkey];
unset($arr[$oldkey]);
Just have a look at robclancy's presenter package, this ServiceProvider handles those things you want to achieve.
GITHUB LINK
Just set the $hidden static for you model to the keys you want to hide:
class User extends Eloquent
{
public static $hidden = 'id';
}
and name them the way you like with get and set functons.

Resources