PHP code example of baril / smoothie

1. Go to this page and download the library: Download baril/smoothie library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

baril / smoothie example snippets


$model->save(['restore' => true]);


$model1 = Article::find(1);
$model2 = Article::find(1);

$model2->title = 'new title';
$model2->save();

$model1->save(['restore' => true]); // the original title will be restored
                                    // because it hasn't changed in `$model1`

$article = Article::create(['title' => 'old title']);
$article->title = 'new title';
$article->update(['subtitle' => 'new subtitle']);

$article->fresh()->title; // "new title"

$article = Article::create(['title' => 'old title']);
$article->title = 'new title';
$article->updateOnly(['subtitle' => 'new subtitle']);

$article->fresh()->title; // "old title"
$article->title; // "new title"
$article->subtitle; // "new subtitle"

$collection = YourModel::all()->sortByKeys([3, 4, 2]);

$collection = Article::findMany([4, 5, 3]); // we're not sure that the article
                                            // with id 4 will be the first of
                                            // the returned collection

$collection = Article::findInOrder([4, 5, 3]); // now we're sure

return [
    // ...
    'providers' => [
        Baril\Smoothie\SmoothieServiceProvider::class,
        // ...
    ],
];

class Post
{
    public function comments()
    {
        return $this->hasMany(Comment::class)->crossDatabase();
    }

    public function category()
    {
        return $this->hasMany(Comment::class)->crossDatabase();
    }
}

class Post
{
    public function tags()
    {
        // same database as parent table (posts):
        return $this->belongsToMany(Tag::class)->crossDatabase('parent');
    }
}

class Tag
{
    public function posts()
    {
        // same database as related table (posts):
        return $this->belongsToMany(Post::class)->crossDatabase('related');
    }
}

Article::where('id', 5)->toSql(); // "SELECT articles WHERE id = ?" -- WTF?
Article::where('id', 5)->debugSql(); // "SELECT articles WHERE id = 5" -- much better

class Blog extends Model
{
    const CREATED_AT = 'blog_creadt';
    const UPDATED_AT = 'blog_upddt';

    protected $primaryKey = 'blog_id';
    protected $keyType = 'string';

    protected $columnsPrefix = 'blog_';
    protected $aliases = [
        'description' => 'blog_desc',
    ];
}

class Article
{
    protected $aliases = [
        'title' => 'meta_title',
        'original_title' => 'title',
    ];
}

class Article
{
    protected $aliases = [
        'title' => 'title',
    ];
    protected $columnsPrefix = 'a_';
}

class Blog extends Model
{
    const CREATED_AT = 'blog_creadt';
    const UPDATED_AT = 'blog_upddt';

    protected $primaryKey = 'blog_id';
    protected $keyType = 'string';

    protected $columnsPrefix = 'blog_';
    protected $aliases = [
        'description' => 'blog_desc',
    ];

    public function getPrDescAttribute($value)
    {
        return trim($value);
    }

    public function getDescriptionAttribute($value)
    {
        return htmlentities($value);
    }
}

$blog->pr_desc; // will return the trimmed description
$blog->desc; // will return the trimmed description
$blog->description; // will return the untrimmed, HTML-encoded description

class MyModel extends Model
{
    use AliasesAttributes, SomeOtherTrait {
        AliasesAttributes::getAttribute insteadof SomeOtherTrait;
        SomeOtherTrait::getAttribute as getUnaliasedAttribute;
        AliasesAttributes::setAttribute insteadof SomeOtherTrait;
        SomeOtherTrait::setAttribute as setUnaliasedAttribute;
    }
}

class MyModel extends Model
{
    use \Baril\Smoothie\Concerns\CachesAccessors;

    protected $cacheable = [
        'some_attribute',
        'some_other_attribute',
    ];
}

$model = MyModel::find(1);
$model->some_attribute; // cached
$model->yet_another_attribute; // not cached

class User extends Model
{
    use \Baril\Smoothie\Concerns\CachesAccessors;

    protected $clearAccessorCache = [
        'first_name' => ['full_name', 'name_with_initial'],
        'last_name' => ['full_name', 'name_with_initial'],
    ];

    public function getFullNameAttribute()
    {
        return $this->first_name . ' ' . $this->last_name;
    }

    public function getNameWithInitialAttribute()
    {
        return substr($this->first_name, 0, 1) . '. ' . $this->last_name;
    }
}

$user = new User([
    'first_name' => 'Jean',
    'last_name' => 'Dupont',
]);
echo $user->full_name; // "Jean Dupont"
$user->first_name = 'Lazslo';
echo $user->full_name; // "Lazslo Dupont": cache has been cleared

$date = Baril\Smoothie\Carbon::createFromFormat('Y-m-d', '2010-10-00');
$date->day; // will return null
$date->isFuzzy(); // will return true if month and/or day is zero

$date = Baril\Smoothie\Carbon::createFromFormat('Y-m-d', '2010-10-00');
$date->format('d/m/Y', 'm/Y', 'Y'); // will display "10/2010"

$date = Baril\Smoothie\Carbon::createFromFormat('Y-m-d', '2010-10-00');
$date->dayOfWeek; // will return 5, because October 1st 2010 was a friday

class Book extends \Illuminate\Database\Eloquent\Model
{
    use \Baril\Smoothie\Concerns\HasFuzzyDates;

    protected $casts = [
        'is_available' => 'boolean',
        'release_date' => 'date', // will allow fuzzy dates
    ];
}

class Book extends \Baril\Smoothie\Model
{
    protected $casts = [
        'is_available' => 'boolean',
        'release_date' => 'date', // will allow fuzzy dates
    ];
}

return [
    'connections' => [
        'mysql' => [
            'strict' => false,
            // ...
        ],
    ],
    // ...
];

class Book extends \Illuminate\Database\Eloquent\Model
{
    use \Baril\Smoothie\Concerns\HasFuzzyDates;

    public function getReleaseDateAttribute()
    {
        return $this->mergeDate(
            'release_date_year',
            'release_date_month',
            'release_date_day'
        );
    }

    public function setReleaseDateAttribute($value)
    {
        $this->splitDate(
            $value,
            'release_date_year',
            'release_date_month',
            'release_date_day'
        );
    }
}

class Book extends \Illuminate\Database\Eloquent\Model
{
    use \Baril\Smoothie\Concerns\HasFuzzyDates;

    public function getReleaseDateAttribute()
    {
        return $this->mergeDate('release_date');
    }

    public function setReleaseDateAttribute($value)
    {
        $this->splitDate($value, 'release_date');
    }
}

class User extends \Illuminate\Database\Eloquent\Model
{
    use \Baril\Smoothie\Concerns\HasMutualSelfRelationships;

    public function friends()
    {
        return $this->mutuallyBelongsToManySelves();
    }
}

$user1->friends()->attach($user2->id);
$user2->friends()->get(); // contains $user1

$user2->friends()->detach($user1->id);
$user1->friends()->get(); // doesn't contain $user2 any more

public function mutuallyBelongsToManySelves(

        // Name of the pivot table (defaults to the snake-cased model name,
        // concatenated to itself with an underscore separator,
        // eg. "user_user"):
        $table = null,

        // First pivot key (defaults to the model's default foreign key, with
        // an added number, eg. "user1_id"):
        $firstPivotKey = null,

        // Second pivot key (the pivot keys can be passed in any order since
        // the relationship is mutual):
        $secondPivotKey = null,

        // Parent key (defaults to the model's primary key):
        $parentKey = null,

        // Relation name (defaults to the name of the caller method):
        $relation = null)

class User extends Model
{
    public function projects()
    {
        return $this->belongsToMany(Project::class, 'project_role_user')->withPivot('role_id');
    }

    public function roles()
    {
        return $this->belongsToMany(Role::class, 'project_role_user')->withPivot('project_id');
    }
}

class User extends Model
{
    use HasMultiManyRelationships;

    public function projects()
    {
        return $this->belongsToMultiMany(Project::class, 'project_role_user');
    }

    public function roles()
    {
        return $this->belongsToMultiMany(Role::class, 'project_role_user');
    }
}

$user->roles()->unfolded()->get();

$roles = $user->projects->first()->roles;

$project = $user->projects->first();
$roles = $project->roles()->all()->get();

$project = $user->projects->first();
$roles = $user->roles()->for('project', $project)->get();

$project = $user->projects->first();
$roles = $user->roles()->withPivot('project_id', $project->id)->get();

$users = User::with('projects', 'projects.roles')->get();
$user = $users->first();
$user->projects->first()->roles; // only the roles of $user on this project

$users = User::with('projects')->withAll('projects.roles')->get();

$users = User::with('projects', 'status')->withAll('projects.roles')->get();
// can be shortened to:
$users = User::withAll('projects', 'projects.roles', 'status')->get();

User::has('projects.roles')->get();

$user->projects()->first()->roles()->attach($admin);
// The new pivot row will receive $user's id in the user_id column.

$user->projects()->first()->roles()->detach($admin);
// Will detach the $admin role from this project, for $user only.
// Other admins of this project will be preserved.

$user->projects()->first()->roles()->all()->attach($admin);
// The new pivot row's user_id will be NULL.

$user->projects()->first()->roles()->all()->detach($admin);
// Will delete all pivot rows for this project and the $admin role,
// whoever the user is.

class User extends Model
{
    use HasMultiManyRelationships;

    public function authorizations()
    {
        return $this->wrapMultiMany([
            'project' => $this->belongsToMultiMany(Project::class, 'project_role_user'),
            'role' => $this->belongsToMultiMany(Role::class, 'project_role_user'),
        ]);
    }
}

$users = User::with('authorizations', 'authorizations.role', 'authorizations.project')->get();

foreach ($users as $user) {
    foreach ($user->authorizations as $authorization) {
        dump($authorization->role);
        dump($authorization->project);
    }
}

$user->authorizations()->attach($pivots, $additionalAttributes);
$user->authorizations()->sync($pivots);
$user->authorizations()->detach($pivots);

$pivots = $user->authorizations->first(); // a Model
$pivots = $user->authorizations->slice(0, 2); // an EloquentCollection of Models
$pivots = ['role_id' => $roleId, 'project_id' => $projectId]; // an associative array keyed by the column names...
$pivots = ['role' => $roleId, 'project' => $projectId]; // ... or the relation names
$pivots = ['role' => Role::first(), 'project' => Project::first()]; // ... where values can be ids or Models
$pivots = [ ['role_id' => $roleId, 'project_id' => $projectId] ]; // an array of such associative arrays
$pivots = collect([ ['role_id' => $roleId, 'project_id' => $projectId] ]); // or even a Collection

class Asset extends Model
{
    use \Baril\Smoothie\Concerns\HasDynamicRelations;
}

// This relation will now be available on all your Assets:
Asset::defineRelation($someName, function () use ($someClass) {
    return $this->belongsTo($someClass);
});

// This relation will now be available on this instance only:
$asset = new Asset;
$asset->defineRelation($someOtherName, function () use ($someOtherClass) {
    return $this->belongsTo($someOtherClass);
});

$entities = $asset->$someName()->where('status', 1)->get(); // regular call
$attachments = $asset->$someOtherClass; // dynamic property

public function up()
{
    Schema::create('articles', function (Blueprint $table) {
        // ... other fields ...
        $table->unsignedInteger('position');
    });
}

class Article extends Model
{
    use \Baril\Smoothie\Concerns\Orderable;

    protected $guarded = ['position'];
}

class Article extends Model
{
    use \Baril\Smoothie\Concerns\Orderable;

    protected $orderColumn = 'order';
    protected $guarded = ['order'];
}

$model = Article::find(1);
$anotherModel = Article::find(10)
$model->moveAfter($anotherModel);
// $model is now positioned after $anotherModel, and both have been saved

$article = new Article();
$article->title = $request->input('title');
$article->body = $request->input('body');
$article->save();

$articles = Article::ordered()->get();
$articles = Article::ordered('desc')->get();

$entity = Article::find(10);
$entity->next(10); // returns a QueryBuilder on the next 10 entities, ordered
$entity->previous(5)->get(); // returns a collection with the previous 5 entities, in reverse order
$entity->next()->first(); // returns the next entity

$models = Article::orderBy('publication_date', 'desc')->get();
$models->map(function($model, $key) {
    return $model->moveToOffset($key);
});

$collection = Article::orderBy('publication_date', 'desc')->get();
$collection->map(function($model, $key) {
    return $model->fresh()->moveToOffset($key);
});

$collection = Article::orderBy('publication_date', 'desc')->get();
// $collection is not a regular Eloquent collection object, it's a custom class
// with the following additional method:
$collection->saveOrder();

$collection = Status::all();
$collection->sortByKeys([2, 1, 5, 3, 4])->saveOrder();

class Article extends Model
{
    use \Baril\Smoothie\Concerns\Orderable;

    protected $guarded = ['position'];
    protected $groupColumn = 'section_id';
}

protected $groupColumn = ['field_name1', 'field_name2'];

class Section extends Model
{
    public function articles()
    {
        return $this->hasMany(Article::class)->ordered();
    }
}

class Post extends Model
{
    use \Baril\Smoothie\Concerns\HasOrderedRelationships;

    public function tags()
    {
        return $this->belongsToManyOrdered(Tag::class);
    }
}

public function belongsToManyOrdered(
        $related,
        $orderColumn = 'position',
        $table = null,
        $foreignPivotKey = null,
        $relatedPivotKey = null,
        $parentKey = null,
        $relatedKey = null,
        $relation = null)

$post->tags()->attach($tag->id); // will attach $tag and give it the last position
$post->tags()->sync([$tag1->id, $tag2->id, $tag3->id]) // will keep the provided order
$post->tags()->detach($tag->id); // will decrement the position of subsequent $tags

$post->tags; // ordered by position
$post->tags()->ordered('desc')->get(); // reverse order
$post->tags()->unordered()->get(); // unordered

// Note that orderBy has no effect here since the tags are already ordered by position:
$post->tags()->orderBy('id')->get();

// This is the proper way to do it:
$post->tags()->unordered()->orderBy('id')->get();

class Post extends Model
{
    use \Baril\Smoothie\Concerns\HasOrderedRelationships;

    public function tags()
    {
        return $this->belongsToManyOrdered(Tag::class)->unordered();
    }
}

$article->tags; // unordered
$article->tags()->ordered()->get(); // ordered

$tag1 = $article->tags()->first();
$tag2 = $article->tags()->last();
$article->tags()->moveBefore($tag1, $tag2);
// now $tag1 is at the second to last position

$article->tags()->setOrder([$id1, $id2, $id3]);

class Post extends Model
{
    use \Baril\Smoothie\Concerns\HasOrderedRelationships;

    public function tags()
    {
        return $this->morphToManyOrdered('App\Tag', 'taggable', 'tag_order');
    }
}

class Tag extends Model
{
    use \Baril\Smoothie\Concerns\HasOrderedRelationships;

    public function posts()
    {
        return $this->morphedByManyOrdered('App\Post', 'taggable', 'order');
    }

    public function videos()
    {
        return $this->morphedByManyOrdered('App\Video', 'taggable', 'order');
    }
}

class File extends \Illuminate\Database\Eloquent\Model
{
    use \Baril\Smoothie\Concerns\BelongsToTree;

    protected $parentForeignKey = 'folder_id';
    protected $closureTable = 'file_closures';
}

$tag = Tag::find($tagId);
$tag->parent_id = $parentTagId; // or: $tag->parent()->associate($parentTag);
$tag->save();

try {
    $tag->delete();
} catch (\Baril\Smoothie\TreeException $e) {
    // some specific treatment
    // ...
    $tag->deleteTree();
}

$tags->descendants()->orderByDepth()->get();

$tags = Tag::with('descendants')->limit(10)->get();

// The following code won't execute any new query:
foreach ($tags as $tag) {
    dump($tag->name);
    foreach ($tag->children as $child) {
        dump('-' . $child->name);
        foreach ($child->children as $grandchild) {
            dump('--' . $grandchild->name);
        }
    }
}

$tags = Tag::getTree();

$tag->ancestors()->orderByDepth();
Tag::with(['descendants' => function ($query) {
    $query->orderByDepth('desc');
}]);

class Tag extends \Illuminate\Database\Eloquent\Model
{
    use \Baril\Smoothie\Concerns\BelongsToOrderedTree;

    protected $orderColumn = 'order';
}

$children = $this->children()->unordered()->orderBy('name');

$lastChild->moveToPosition(1);

class Country extends Model
{
    use \Baril\Smoothie\Concerns\Cacheable;

    protected $cache = 'redis';
}

class Country extends Model
{
    use \Baril\Smoothie\Concerns\Cacheable;

    public function getCache()
    {
        return app('cache')->store('redis')->tags(['referentials']);
    }
}

class Country extends Model
{
    use \Baril\Smoothie\Concerns\Cacheable;

    protected static function loadFromDatabase()
    {
        return static::with('languages')->get();
    }
}

Country::where('code', 'fr_FR')->usingCache()->get();

class User extends Model
{
    public function country()
    {
        return $this->belongsTo(Country::class)->usingCache();
    }
}

$user->country()->usingCache(false)->get();

class User extends Model
{
    use \Baril\Smoothie\Concerns\CachesRelationships;

    public function groups()
    {
        return $this->belongsToMany(Group::class)->usingCache();
    }
}
bash
php artisan smoothie:fix-pivots "App\\YourModelClass" relationName

class AddPrimaryKeyToProjectRoleUserTable extends Migration
{
    public function up()
    {
        Schema::table('project_role_user', function (Blueprint $table) {
             $table->increments('id')->first();
        });
    }
    public function down()
    {
        Schema::table('project_role_user', function (Blueprint $table) {
             $table->dropColumn('id');
        });
    }
}
bash
php artisan smoothie:grow-tree "App\\YourModel"
bash
php artisan smoothie:grow-tree "App\\YourModel" --migrate
bash
php artisan smoothie:fix-tree "App\\YourModel"