This module can automatically sync Eloquent models to Firebase Realtime database.
To enable synching use the SyncWithFirebase
trait in your Model
use Plokko\LaravelFirebase\Traits\SyncWithFirebase;
class MyModel extends Model
{
use SyncWithFirebase;
//...
}
This model will add the syncWithFirebase
method that manually syncs the model to Firebase and will be triggered at each model modification done throught eloquent(save,update,delete,restore).
You can customize what will be synched with Firebase via the toFirebase
method otherwise the output of toArray will be used instead
use Plokko\LaravelFirebase\Traits\SyncWithFirebase;
class MyModel extends Model
{
use SyncWithFirebase;
//...
/**
* Returns the data that will be synched with firebase
* @return array
**/
function toFirebase(){
return [
'id' => $this->id,
'name' => $this->name,
'custom'=> 'value',
//....
];
}
}
By default the model will be synchromized to Firebase using the table name (ex. User model using users table will be sync to /users);
you can change this behaivour by extending the getFirebaseReferenceName
method and returning a custom reference name
/**
* @return string reference name
*/
public function getFirebaseReferenceName(){
return 'my_custom_reference';// default : $this->getTable();
}
Sometimes you want to serialize to firebase data from othe related models but the changes in the related model will not be automatically updated on the base model and vice-versa.
You can extend the model synchronization to related models using the SyncRelatedWithFirebase
trait in your Model and extend the getRelationsToSyncWithFirebase()
function to return an array of relations you want to keep in sync
use Plokko\LaravelFirebase\Traits\SyncWithFirebase;
class MyModel extends Model
{
use SyncWithFirebase,
SyncRelatedWithFirebase;
/**
* Specifies the relations that needs to be automatically synched with firebase
* @return array relations to be synched with firebase, default []
*/
protected function getRelationsToSyncWithFirebase(){
return [
'myRelation',
'myOtherRelation'
];
}
public function myRelation(){
return $this->belongsToMany(OtherModel::class);
}
}
This trait will automatically sync related model every time a m-n relation is changed or the model is saved.
Sometimes the content of a model must be synchronized with an unrelated or you need to trigger the sync just in some conditions.
You can customize what an when to trigger related mode synchromization by changing the return value of getRelationsToSyncWithFirebase
:
accepted value for the array values are:
- simple: 'relation_name' - simple relation synching
- with filter: 'relation_name' => function($query){} - filter the relationship
- Custom query: function(){} - return a query to sync with Firebase
function getRelationsToSyncWithFirebase(){
return [
'target',//Normal
'client'=>function($query){$query->where('is_premium','=',1);},//With filter
function(){ return UnrelatedModel::where('condition','value');},//Custom query
];
}