10 packages to easily deal with eloquent in laravel

As we all know laravel eloquent has changed the way we deal database ! so here are the lis of 10 packages to easily deal with eloquent in laravel
#1 DB Blade Compiler
Render Blade templates from Eloquent Model Fields
This package generates and returns a compiled view from a blade-syntax field in your Eloquent model
Installation (Laravel 5.x)
Require this package in your composer.json and run composer update (or run composer require flynsarmy/db-blade-compiler:2.* directly):
"flynsarmy/db-blade-compiler": "2.*"
After updating composer, add the ServiceProvider to the providers array in app/config/app.php
'FlynsarmyDbBladeCompilerDbBladeCompilerServiceProvider',
You have to also publish the config-file
php artisan vendor:publish
ElasticCat
installation
- Add the package to your
composer.jsonfile and runcomposer update:
{
"require": {
"argb/elastic-cat": "^1.0"
}
}
- Add the service provider to your
config/app.phpfile, inside theprovidersarray:'ArgbElasticCatBouncyServiceProvider' - Publish the config file by running the following command in the terminal:
php artisan vendor:publish - Edit the config files:
config/bouncy.phpfor Bouncy specific options andconfig/elasticsearch.phpfor configuring the ElasticSearch client.
#3 Elasticquent
Elasticsearch for Eloquent Laravel Models Elasticquent makes working with Elasticsearch and Eloquent models easier by mapping them to Elasticsearch types. You can use the default settings or define how Elasticsearch should index and search your Eloquent models right in the model.
#4 Sofa/Eloquence
Easy and flexible extensions for the Eloquent ORM (Laravel 5.1+ LTS).
Currently available extensions:
Searchablequery – crazy-simple fulltext search through any related model (based on https://github.com/nicolaslopezj/searchable only written from scratch & greatly improved)Validable– self-validating modelsMappable-map attributes to table fields and/or related modelsMetable– meta attributes made easyMutable– flexible attribute get/set mutators with quick setup (with help of Romain Lanz)Mutator– pipe-based mutating
#5 eloquent-base-model
#6 Eloquence
Eloquence is a package to extend Laravel 5’s base Eloquent models and functionality. It provides a number of utilities and classes to work with Eloquent in new and useful ways, such as camel cased attributes (for JSON apis), count caching, uuids and more.
Installation
Install the package via composer:
composer For Laravel 4, please install the 1.1.4 release. Please note that this is no longer supported and won’t receive any new features, only security updates.
composer Usage
First, add the eloquence service provider to your config/app.php file:
'EloquenceEloquenceServiceProvider',
It’s important to note that this will automatically re-bind the Model class that Eloquent uses for many-to-many relationships. This is necessary because when the Pivot model is instantiated, we need it to utilise the parent model’s information and traits that may be needed.
You should now be good to go with your models.
#7 Eloquent Enhancements
This package aims to provide extra functionalities to Laravel’s Eloquent. The functionalities, for now, are provided in form of traits, so you don’t have to change your models structure.
Error
This trait add two methods to your models.
use SigepEloquentEnhancementsTraitsError
setErrors
Receives a MessageBag and set in $errors property. The SaveAll uses it to store errors and allow you to use them in your controllers or views.
setErrors(IlluminateSupportMessageBag $errors)
errors
Returns errors setted by setErrors(). Create a empty MessageBag if errors is not defined.
errors()
SaveAll
This tait add the ability to save related objects in just one call. For example, if you have a User model who is related to Phone model, in a hasMany relationship, you can save a user with many phones with just one method call.
use SigepEloquentEnhancementsTraitsSaveAll;
Consider the following models:
class User extends Eloquent
{
use SigepEloquentEnhancementsTraitsErrors;
use SigepEloquentEnhancementsTraitsSaveAll;
public function phones()
{
return $this->hasMany('Phone');
}
}
class Phone extends Eloquent
{
public function user()
{
return $this->belongsTo('User');
}
}
We strongly suggest that you use model’s observers to validate your data and use the setErrors() to transport validation messages. Is the best way to validate related data when you use this trait.
You can create a user with two phones using the createAll() method.
$input = array(
'name' => 'Bob',
'email' => '[email protected]',
'phones' => array (
array('number' => '1111111'),
array('number' => '2222222'),
),
);
$bob = new User();
$bob->createAll($input);
Note that we have a key with the name of the relationship that we create on User model. This is necessary so SaveAll knows which model are involved and how save your data. If everything is fine, createAll will return true. Else, will return false.
Now, if you need to edit a number using the User model (when you have a form that shows all data, for example), you can use the saveAll() method.
$input = array(
'name' => 'Bob',
'email' => '[email protected]',
'phones' => array (
array('id' => 1, 'number' => '111-1111'),
array('id' => 2, 'number' => '222-2222'),
),
);
$bob = User::find(1); // assuming bob have the id = 1
$bob->saveAll($input);
See that we add the id from the number on the array. This is necessary so SaveAll knows that is not a new record, but an update.
You do something similar when you need to remove a related model. You just need to pass the _delete key:
$input = array(
'name' => 'Bob',
'email' => '[email protected]',
'phones' => array (
array('id' => 1, '_delete' => true),
),
);
$bob = User::find(1); // assuming bob have the id = 1
$bob->saveAll($input);
In this case, the phone #1 will be removed. The other properties are not necessary, just the id and the _delete key.
SaveAll can handle BelongsToMany relationships to. You just have to use like the examples above. But that kind of relationship has one particularity. If the pivot table has more columns them just the foreign keys, you can create a Relationship Model to handle the validations (assuming that you are using model observers to do the validation like suggested before :) ).
# 8 Eloquent Filterable
With this package, you can optimize query clauses calling before or after the filter. You can manage your queries from a single interface.
Installation
PHP 5.4+ or HHVM 3.3+, and Composer are required. To get the latest version of Eloquent Filterable, simply add the following line to the require block of your composer.json file:
"require": {
"mayoz/eloquent-filterable": "~1.0"
}
You’ll then need to run composer install or composer update to download it and have the autoloader updated. Or use to shortcut installed through terminal:
composer require mayoz/eloquent-filterable ~1.0
Usage
- Create your query filters.
- Create your Eloquent models.
- Define
Filterabletrait and use the query filters in the Eloquent model.
Create Filters
All filters should be extend MayozFilterFilter abstract class. Thus, can be used before and after methods in your filters.
The Before Method
The before method responsible to position the head of the WHERE clause of the query. For example; we need published = 1 of query WHERE clause. However, this clause would like to work on before the other clauses.
<?php namespace AppFilters;
use MayozFilterFilter;
class PublishedFilter extends Filter
{
/**
* The first executable filter clause.
*
* @param mixed $query
* @return void
*/
public static function before($query)
{
$query->where('published', '=', 1);
}
}
The After Method
The after method responsible to position the end of the WHERE clause of the query. For example, if need status = 'active' of query WHERE clause. However, this clause would like to work on after the other clauses.
<?php namespace AppFilters;
use MayozFilterFilter;
class StatusActiveFilter extends Filter
{
/**
* The last executable filter clause.
*
* @param mixed $query
* @return void
*/
public static function after($query)
{
$query->where('status', '=', 'active');
}
}
Create Model
Create your model file. If you want to manage queries add the Filterable trait your model file. And than, assign the all associative filters to $filters variable. Consider the following example:
<?php namespace App;
use IlluminateDatabaseEloquentModel;
use MayozFilterFilterable;
class Post extends Model
{
use Filterable;
/**
* The attributes that should be filter.
*
* @var array
*/
protected $filters = [
'AppFiltersStatusActiveFilter',
'AppFiltersPublishedFilter'
];
// other things...
}
Important: The order of the filter is important when adding (if need multiple before or after filters) query clause. The before filters are added the head of the clause according to the reference sequence. Likewise, the after filters.
Debug
Now the Post model is ready to use. You ready? Okay, we’re testing the query. Don’t forget to enable the query logging for examine the model queries.
$model = AppPost::where('views', '>', 100)->get();
Query logging output:
SELECT *
FROM `posts`
WHERE `published` = 1 # added by automatic filter.
AND `views` > 100 # user defined where clause
AND `status` = 'active' # added by automatic filter.
Why Use?
For example, you might want to show only the approved text of the visitors on the site. However, administrators can see them all. Create a new extended filter:
<?php namespace AppFilters;
use Auth;
use MayozFilterFilter;
class StatusActiveFilter extends Filter
{
/**
* The last executable filter clause.
*
* @param mixed $query
* @return void
*/
public static function after($query)
{
# assume, the `users` table has `role` field.
if (array_get(Auth::user(), 'role') != 'administrator')
{
$query->where('status', '=', 'active');
}
}
}
Hocus, pocus! Visitors will display only the active posts. But administrator display all. Ok?
#9 EloquentDataTable
Eloquent compatible DataTable plugin for server side ajax call handling. If you are familiar with eloquent and would like to use it in combination with datatables this is what you are looking for.
Usage
Step 1: Install through composer
composer require livecontrol/eloquent-datatable
Step 2: Add DataTables javascript and set it up
For more information check out the datatables manual. Make sure you have csrf requests working with jquery ajax calls.
var table = $('#example').DataTable({
"processing": true,
"serverSide": true,
"ajax": {
"url": "<url to datatable route>",
"type": "POST"
}
});
Step 3: Use it
$users = new ModelsUser();
$dataTable = new LiveControlEloquentDataTableDataTable($users, ['email', 'firstname', 'lastname']);
echo json_encode($dataTable->make());
Optional step 4: Set versions of DataTables plugin.
Just initialize the DataTable object as you would normally and call the setVersionTransformer function as in the following example (for version 1.09 of DataTables):
$dataTable->setVersionTransformer(new LiveControlEloquentDataTableVersionTransformersVersion109Transformer());
By default the plugin will be loading the transformer which is compatible with DataTables version 1.10.
#10 Eloquent Activatable
Creating (de-) activatable Eloquent Models made easy.
Installation
First, you’ll need to add the package to your composer.json and run composer update.
{
"require": {
"niclasleonbock/eloquent-activatable": "dev-master"
},
}
Because Eloquent Activatable uses traits and global query scopes you will need to run PHP 5.4.0 and Laravel 4.2.0 or higher.
Now, simply add a datetime column called activated_at to your table and use the ActivatableTrait (niclasleonbockEloquentActivatableTrait) in your Eloquent model.
Migration
<?php
$table->datetime('activated_at')->nullable();
Your Model
<?php
use niclasleonbockEloquentActivatableTrait;
class Topic extends Eloquent
{
use ActivatableTrait;
// ...
}
And you’re done!
Use
withDeactivated()
By default all database queries will be filtered so that only activated data sets are shown. To also show deactivated data sets you may use the withDeactivated method on the query builder.
<?php
$allTopics = Topic::withDeactivated()->get();
onlyDeactivated()
To get only deactivated data sets use the onlyDeactivated method.
<?php
$onlyDeactivatedTopics = Topic::onlyDeactivated()->get();
activated()
To check whether a data set is deactivated you may use the activated method.
<?php
echo 'My topic is ' . ($topic->activated() ? 'activated' : 'deactivated');
activate()
To activate a data set use the activate method.
<?php
$topic->activate();
$topic->save();
echo 'My topic is now ' . ($topic->activated() ? 'activated' : 'deactivated');
deactivate()
To deactivate a data set use the deactivate method.
<?php
$topic->deactivate();
$topic->save();
echo 'My topic is now ' . ($topic->activated() ? 'activated' : 'deactivated');
Customization
Sometimes the column name activated_at may not fit even though the functionality does. To change the name you can easily override the protected $activatedAtColumn variable or the public getActivatedAtColumn method.