At QuickAdminPanel, our goal is to save the developer time. Laravel Eloquent is a good example – his “magic” helps do things faster. But in addition to that, there are a lot of packages that can help even more. Let’s review the most popular.
Notice: Some packages have similar (almost identical) packages created by other developers, I added these links at the end of each package review, if necessary.
1. Audit Laravel: Save the model for modification of the models
URL:
Package which records the modifications of your eloquent model recordings as a “audits” allets, in a separate DB table.
The use is very simple. Everything you have to do in your model:
use Illuminate\Database\Eloquent\Model;
use OwenIt\Auditing\Contracts\Auditable;
class Article extends Model implements Auditable
{
use \OwenIt\Auditing\Auditable;
// ...
}
And then you can get all the “audits” by your model:
// Get first available Article $article = Article::first(); // Get all associated Audits $all = $article->audits; // Get first Audit $first = $article->audits()->first(); // Get last Audit $last = $article->audits()->latest()->first(); // Get Audit by id $audit = $article->audits()->find(4);
Official website: laravel-auditing.com
Article on Laravel News: Follow the Laravel model changes with Laravel audit
Similar package: Venturecraft / revisionable
2. Laravel-Soft Cascade: DELETE & RESTORE cascade when you use Laravel Softdeletes
URL:
Soft-Réletes is a major ready-to-use eloquent function, but it does not work with foreign keys and -> ONDELETE (‘Cascade’); migration. This package will solve this problem.
Use. In your model, use this:
use \Askedio\SoftCascade\Traits\SoftCascadeTrait; protected $softCascade = ['profiles']; // names of your relations
After that, when you can delegate the software, all children’s entries will be automatically deleted smoothly. It also works with restore() function:
User::first()->delete(); User::withTrashed()->first()->restore();
More information: cascading softdeletes with Laravel 5
Similar package: Michaeldyrynda / Laravel-Cascade-Soft-Réletes
3. Spatie / Laravel-Schemess-Attributes: Add diagram attributes to the eloquent models
URL:
This package provides a line which, when applied to a model, allows you to store Arbritrary values in a single JSON column.
The preparation of the model is a little more than a line of code, but always completely understandable, you must define an attribute, an accessory and a scope:
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Builder;
use Spatie\SchemalessAttributes\SchemalessAttributes;
class TestModel extends Model
{
// ...
public $casts = [
'extra_attributes' => 'array',
];
public function getExtraAttributesAttribute(): SchemalessAttributes
{
return SchemalessAttributes::createForModel($this, 'extra_attributes');
}
public function scopeWithExtraAttributes(): Builder
{
return SchemalessAttributes::scopeWithSchemalessAttributes('extra_attributes');
}
}
And then you can simply use this attribute as a property inside your model:
$yourModel->extra_attributes->name="value"; $yourModel->extra_attributes->name; // Returns 'value'
Or as a table:
// All existing schemaless attributes will be replaced $yourModel->extra_attributes = ['name' => 'value']; $yourModel->extra_attributes->all(); // Returns ['name' => 'value']
4. Awssat / Laravel-visits: visits to the track model
URL:
This package allows you to save visits to a page / model. He does it using Redis, so you need to configure this:
'laravel-visits' => [
'host' => env('REDIS_HOST', '127.0.0.1'),
'password' => env('REDIS_PASSWORD', null),
'port' => env('REDIS_PORT', 6379),
'database' => 3, // anything from 1 to 15, except 0 (or what is set in default)
],
And then you can save visits with a line of code:
visits($post)->increment();
Counting messages is also easy:
visits($post)->count();
It also has a logic of limiting the journalization of the visit once by IP every 15 minutes, but it is also configurable.
The best part comes if you want to aggregate the data:
visits($post)->countries(); // top countries
visits($post)->refs(); // referers
visits('App\Post')->top(10); // Top 10 posts
Learn more about Laravel News: Count Models with the Laravel Visit package
5. Cybercog / Laravel-Love: React on eloquent models with tastes or aversions
URL:
If you have publications or comments that can be appreciated / hated, this package is for you.
The preparation of the model looks like this:
use Cog\Contracts\Love\Likeable\Models\Likeable as LikeableContract;
use Cog\Laravel\Love\Likeable\Models\Traits\Likeable;
use Illuminate\Database\Eloquent\Model;
class Article extends Model implements LikeableContract
{
use Likeable;
}
And then you can do things like:
$user->like($article); $article->likeBy(); // current user $article->likeBy($user->id); $user->unlike($article); $article->unlikeBy(); // current user $article->unlikeBy($user->id); $article->likesCount; // get likes for article $article->collectLikers(); // Get collection of users who liked model
Learn more about Laravel News: Laravel Love: Likes and does not like for eloquent models
6. Spatie / Laravel-Tags: Add tags and tag behavior to your Laravel application
URL:
The only thing you need to do is add the Hastags Train to an eloquent model to make it taggable.
use Spatie\Tags\HasTags;
class NewsItem extends Model
{
use HasTags;
...
}
And then do not hesitate to use it:
//create a model with some tags
$newsItem = NewsItem::create([
'name' => 'testModel',
'tags' => ['tag', 'tag2'], //tags will be created if they don't exist
]);
//attaching tags
$newsItem->attachTag('tag3');
$newsItem->attachTags(['tag4', 'tag5']);
//syncing tags
$newsItem->syncTags(['tag1', 'tag2']); // all other tags on this model will be detached
//retrieving models that have any of the given tags
NewsItem::withAnyTags(['tag1', 'tag2'])->get();
//retrieve models that have all of the given tags
NewsItem::withAllTags(['tag1', 'tag2'])->get();
More information – in the authors’ article: an opinion beacon package for Laravel applications
Similar package: RtConner / Laravel-Tagging
7. Spatie / Laravel-Sluggable: Generate slugs when saving eloquent models
URL:
This package automatically generates slugs from your title / name or any field you want. Here’s how you specify in the model:
use Spatie\Sluggable\HasSlug;
use Spatie\Sluggable\SlugOptions;
use Illuminate\Database\Eloquent\Model;
class Article extends Model
{
use HasSlug;
/**
* Get the options for generating the slug.
*/
public function getSlugOptions() : SlugOptions
{
return SlugOptions::create()
->generateSlugsFrom('name')
->saveSlugsTo('slug');
}
}
And then the magic occurs:
$model = new Article(); $model->name="activerecord is awesome"; $model->save(); echo $model->slug; // outputs "activerecord-is-awesome"
You can also specify different slugs for different languages, also configure what is going on when updating the recording, which separator to use (“-” or “_”) and more settings.
More information from authors: a PHP 7 / Laravel package to create slugs
Similar package: CVIEBROCK / Eloquent-Tousque
8. Spatie / Eloquent-Stratable: Triable behavior for eloquent models
URL:
This package provides a line that adds triable behavior to an eloquent model.
Here is how you specify the triable field of the model:
use Spatie\EloquentSortable\Sortable;
use Spatie\EloquentSortable\SortableTrait;
class Article extends Eloquent implements Sortable
{
use SortableTrait;
public $sortable = [
'order_column_name' => 'order_column',
'sort_when_creating' => true,
];
...
}
Then the column is automatically filled:
$article = new Article(); $article->save(); // order_column for this record will be set to 1 $article = new Article(); $article->save(); // order_column for this record will be set to 2 $article = new Article(); $article->save(); // order_column for this record will be set to 3 //the trait also provides the ordered query scope $orderedRecords = Article::ordered()->get();
9. Dimsav / Laravel-Translable: a Laravel package for multilingual models
URL:
We have a separate article for 10 best Laravel packages for multi-year projects, and this is the obvious leader on the market.
You must create database migrations according to this scheme:
Schema::create('countries', function(Blueprint $table)
{
$table->increments('id');
$table->string('code');
$table->timestamps();
});
Schema::create('country_translations', function(Blueprint $table)
{
$table->increments('id');
$table->integer('country_id')->unsigned();
$table->string('name');
$table->string('locale')->index();
$table->unique(['country_id','locale']);
$table->foreign('country_id')->references('id')->on('countries')->onDelete('cascade');
});
The next step is to configure your main model and also the related model for translations:
// models/Country.php
class Country extends Eloquent {
use \Dimsav\Translatable\Translatable;
public $translatedAttributes = ['name'];
protected $fillable = ['code'];
}
// models/CountryTranslation.php
class CountryTranslation extends Eloquent {
public $timestamps = false;
protected $fillable = ['name'];
}
Then you can fill and use translations, like this:
$data = [
'code' => 'gr',
'en' => ['name' => 'Greece'],
'fr' => ['name' => 'Grèce'],
];
$greece = Country::create($data);
echo $greece->translate('fr')->name; // Grèce
Similar package: space / laravel translatable
10. Space / Laravel-Medialibrary: associate files with eloquent models
I intentionally left this brilliant package the last on the list, because I suppose / I hope everyone knows. It has more than a million downloads overall. But for those who don’t know it …
Here’s how you configure your models to have media.
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Spatie\MediaLibrary\HasMedia\HasMedia;
use Spatie\MediaLibrary\HasMedia\HasMediaTrait;
class News extends Model implements HasMedia
{
use HasMediaTrait;
...
}
And then you can attach all the multimedia files to the model:
$newsItem = News::find(1); $newsItem ->addMedia($pathToFile) ->toMediaCollection();
Finally, here is how to recover these files:
$mediaItems = $newsItem->getMedia(); $publicUrl = $mediaItems[0]->getUrl(); $publicFullUrl = $mediaItems[0]->getFullUrl(); //url including domain
In the database, the records are stored in a media Table that uses polymorphic relationships.
So, that’s all, the 10 hand -selected packages, as well as their similar packages. Something I missed? Other packages to improve eloquent?