I am using Slim Framework with eloquent ORM for database operations, I want to store encrypted data in the database(MYSQL) for fewer columns of particular tables.
I have tried with AES_ENCRYPTin eloquent model which stored the data well with mutators like,
class MyDataModel extends Model {
public function setProcessDataAttribute($value)
{
$this->attributes['process_data'] =
DB::raw("AES_ENCRYPT('".$value."', '12345')");
}
}
Now, I want to decrypt with the MYSQL function AES_DECRYPT, is there any way to use MYSQL functions in the eloquent model?
I am not sure how can I override the find, get methods in my model.
In laravel 5, recommend use his AES encryption:
$newEncrypter = new \Illuminate\Encryption\Encrypter('your key or app_key#env', config('app.cipher') );
$decrypted = $newEncrypter->decrypt('your encrypted data');
Related
my problem is that i can't map database function to use it in object property like computed column but for different tables with relation. My relation is SizeItem to Review (one to many)
I have IEntityTypeConfiguration
internal class SizeItemConfiguration : IEntityTypeConfiguration<SizeItem>
{
public const string TableName = "size_items";
public void Configure(EntityTypeBuilder<SizeItem> builder)
{
builder.ToTable(TableName);
builder.Property(p => p.Id)
.UseHiLo("size_item_hilo");
}
}
And want to compute an average rating from Review entities related to a SizeItem.
I tried to find examples to use database functions and EF Core functions but nothing works.
How can I get computed SizeItem.AverageRating for every sql command? May be code will looks like:
builder.Property(p => Functions.Average(p.Reviews.Select(x => x.Rating)));
User-defined function mapping doesn't work for me because I'm using Repository pattern.
For Dynamic column supported in Maria-DB and in MySQL we have JSON column type. For one of our projects, we should be implementing a database for Maria-DB (not Mysql).
The Dynamic Column is supported using yii2-dynamic-ar package.
how can can override Eloquent orm in Laravel to add dynamic-columns. in the Yii package which added this feature to ActiveRecord this classes can override ActiveRecord class
implementations classes in Yii framework to support in ActiveRecord ORM:
DynamicActiveRecord.php
DynamicActiveQuery.php
I just created package for handling MariaDB dynamic Column using eloquent and query builder.
To install package run this command:
composer require halalsoft/laravel-dynamic-column
You can start using the package by adding the HasDynamicColumn trait and use Dynamic as attribute cast to your models.
An example:
use Illuminate\Database\Eloquent\Model;
use Halalsoft\LaravelDynamicColumn\Dynamic;
use Halalsoft\LaravelDynamicColumn\HasDynamicColumn;
class MyModel extends Model
{
use HasDynamicColumn;
protected $casts
= [
'the_column' => Dynamic::class,
];
}
Now You can use dynamic column like json column using eloquent or query builder:
$modelData = MyModel::find(1);
$columnData = $modelData->the_column;
$columnData['data1'] = 'value';
$columnData['data2'] = 'value2';
$modelData->the_column = $columnData;
$modelData->save();
You can also create data field as array
$newData = MyModel::create([
'other_column' => 'this just another column data',
'the_column' => ['data1'=>'value1','data2'=>'value2']
]);
to update a json field/key you use, you may use the -> operator when calling the update method:
$page->update(['content->data1' => 'value1new']);
or you can still update whole column using normal array:
$page->update(['content' => ['data1'=>'value1new','data2'=>'value2new']]);
You can set as array using other method like updateOrCreate(), firstOrCreate(), etc.
This package also support query builder using:
Model::query()->where('the_column->data1', 'value1')->first();
This package is still new, if any issue or request just go to github issue
You can have a cast defined for the column in the Model class
//Model class
protected $casts = ['my_column' => 'array];
You can define the datatype for the column as text if you want or json, with the cast defined, you will be able to work with the column data as associative array.
There's also a package to add json datatype in migration for mariadb - it may be of help
https://github.com/ybr-nx/laravel-mariadb
In MySql I have two tables: staff and certifications. There is a one-to-many relationship where staff.pk = certifications.fk.
For each staff member, I need to insert their multiple certifications.name values into a JSON column in the staff table.
I also need to be able to read this as an array cast in a Laravel - does that mean it needs to be a JSON array, rather than a JSON object?
UPDATE:
I need to do this as a batch process, since I have many thousands of records to process. That's why I am concencentrating on the raw SQL. Instantiating Eloquent models would not work from a performance perspective.
you can use Accessors & Mutators
namespace App;
use Illuminate\Database\Eloquent\Model;
class Staff extends Model
{
//assuming you have certificates column in staff table to store json data
public function setCertificatesAttribute($certificates)
{
$this->attributes['certificates'] = json_encode($certificates);
}
public function getCertificatesAttribute()
{
if($certificates != null){
return json_decode($certificates, true); //force to array
}
return []; //default empty array
}
}
Now if you create or update staff
Staff::create([
'name' => 'Staff1',
'certificates' => ['certificate1', 'certificate2']
]);
Then it will automatically saved as a json data in your staff table. And when you fetch data using $staff->certificates then it will return you array.
hope it may solve your problem
I'm creating an online tool for companies that each have a set of users in Laravel.
When a user is connected, he has a $connected_company_id variable
For every SELECT request (called by ::all(), find(), ...), i would like to add the condition: where company_id = $connected_company_id. I have found this post: laravel set an automatic where clause, but it doesn't work by overriding newQuery().
For every INSERT request, i would like to add the company_id.
Is this possible without changing my code inside all the controllers ?
I thought about extending Eloquent with customEloquent, and then make my models extend customEloquent, but I don't know how to write the code for customEloquent and if it could work.
Well, you could make use of the Eloquent Model Events. I assume you have the connected_company_id stored in the Session company_id
class BaseModel extends Eloquent{
public static function boot(){
parent::boot();
//Column to inject when inserting
static::creating(function ($obj){
$obj->company_id = Session::get('company_id');
});
//Column to inject when updating
static::updating(function ($obj){
$obj->company_id = Session::get('company_id');
});
}
}
You can extend the BaseModel class on all the models that you want the company_id to be inserted or updated. Take a look at Eloquent Model Events for more information.
The above code will automatically insert or update the company_id to the model that you extend the BaseModel to. When you do a Model::all() or Model::get(), you automatically get the company_id on that Model and you can also perform searches as you requested on Point `
Hope this helps.
well, you can just add the company id to the find query.
Model::where("company_id","=",$company_id):
Or you can create a scope:
class theModel extends Eloquent {
static $company_id;
static for_company($company_id){
self::company_id=$company_id;
return __CLASS__;
}
public function scopeCompany($query)
{
return $query->where('company_id', '=', self::company_id);
}
}
//And later
$scope=theModel::for_company($company_id);
$res=$scope::company->where(...);
Disclaimer: I haven't tried this. Just a solution I constructed. Let me know if this works. This will not work under PHP 5.3
I have few questions about Doctrine and MySQL working together. I don't understand it in 100%
I read somewhere that Doctrine can cooperate with MySQL DB. How it happens?
How do I load my DB?
How do I operate on my MySQL tables via doctrine (I'm no thinking about creating new ones)?
Does Doctrine save automatically changes to database?, if not then how to?
Some sample of code would be great. I don’t care too much about language can be in PHP, Yaml and others.
a) please specify more what you maen with "load DB". Doctrine is an ORM.
check here docs:
http://www.doctrine-project.org/projects/orm/1.2/docs/hu (check cookbook)
b) operations with tables with Doctrine are with DQL, example:
$q = Doctrine_Query::create()
->from('User u')
->leftJoin('u.Phonenumbers p');
$q->execute(); //you get a doctrine collection to iterate results of query
c)NO you need to save the object
$account = new Account();
$account->name = 'test 1';
$account->amount = '100.00';
$account->save();
here is account class
class Account extends Doctrine_Record
{
public function setTableDefinition()
{
$this->hasColumn('name', 'string', 255);
$this->hasColumn('amount', 'decimal');
}
}