Package with small support traits and classes for the Laravel Eloquent models

Overview

Laravel's Eloquent support package

Contains a set of traits for the eloquent model. In future can contain more set of classes/traits for the eloquent database.

Installation

composer require pion/laravel-support-eloquent

Attribute value altering traits

Set of traits that will change the attribute value.

CleanHTMLFromAttributeTrait

Enables automatic attribute value cleaning from HTML for all attributes, by limiting only desired by $cleanAttributes property or by limiting which attributes can have html $dontCleanAttributes. You can use the $stripHtmlTags property to specify tags which should not be stripped.

For manual usage use CleanHTMLTrait with tryToCleanAttributeValue($key, $value) method.

Null only given attributes:

public $cleanAttributes = [
    "name"
];

Don't null provided attributes:

public $dontCleanAttributes = [
    "name"
];

NullEmptyStringAttributeTrait

Enables the automatic nulling of empty string value (like from post or set). You can provide list of columns keys to allow only specified columns (use $nullEmptyAttributes) to be set to null or you can provide a list of columns keys to ignore while trying to null the value (use $dontNullEmptyAttributes). They can be set in construct or as property.

For manual usage use NullEmptyStringTrait with tryToNullAttributeValue($key, $value) method.

Null only given attributes:

public $nullEmptyAttributes = [
    "name"
];

Don't null provided attributes:

public $dontNullEmptyAttributes = [
    "name"
];

NormalizeFloatAttributeTrait

Converts float string to float value with comma support (floatval fails to convert 13,3 to 13.3) by setting list of attributes via $normalizeFloatAttributes.

public $normalizeFloatAttributes = [
    'price',
    'discount',
];

For manual usage use NormalizeFloatTrait with tryToNormalizeFloatAttributeValue($key, $value) method.

DateAttributeValueTrait

Converts allowed attributes (by settings $dateAttributes) to carbon instance without any format limitation. Tries to parse any format.

public $dateAttributes = ['custom_date'];

For manual usage use DateAttributeTrait with tryToConvertAttributeValueToDate($key, $value) method.

All values are converted via toArray method to default format. You can customize date formats by attribute by setting dateFormats:

public $dateFormats = [
    'born' => 'Y-m-d'
];

Running multiple trait functions

Using all attributes traits

To apply all traits that are currently implemented use AlterAttributeValueTrait.

Manual

Unfortunately traits can't override same method (in this case setAttribute). For this purpose, you must override the setAttribute method by your self and call the desired trait method by your self.

Every trait has own manual method that tries to alter the value. Use appropriate trait (NullEmptyStringTrait, CleanHTMLTrait, etc).

For chaining the value you can use helper function alter_attribute_value.

/**
 * Set a given attribute on the model.
 *
 * @param  string $key
 * @param  mixed  $value
 */
public function setAttribute($key, $value)
{
    parent::setAttribute($key, alter_attribute_value($key, $value, $this, [
        'tryToCleanAttributeValue',
        'tryToNullAttributeValue'
    ]));
}

Relation Traits

RelationJoinTrait

Enables to create a join SQL statement that will construct the relation model and stores it into relations (so you don't need to eager load the relation). The model is created from the relation function (the key you provide). You can create a custom aliases to fix custom relation naming.

In default usage will load all columns from schema, for better perfomance you can provide a set of columns to load from the relation. You can't provide a '*' as column.

$relationAliases - A list of relations that has different method name than the table.

Can be defined in model like this:

"type" ];">
protected $relationAliases = [
    "activity_type" => "type"
];

Then you can call it in standard way modelJoin("type") for a ActivityType model class.

Example

The basic method support custom columns, where condition, join operator and join type.

All columns
get()">
Model::modelJoin("type")->get()
Desired columns (recommended)
get();">
Model::modelJoin("type", ["name", "id", "color"])->get();

Then you can get the object by standard relation way:

$model->type->color

But be carefull, can be null (default is LEFT connection)!

Desired columns with inner join
get();">
Model::modelJoin("type", ["name", "id", "color"], "inner")->get();
Method

Docs is provided in code.

modelJoin($query, $relation_name, $operatorOrColumns = '=', $type = 'left', $where = false, $columns = array())

Advanced example

Docs is provided in code. Uses table as a relation function.

joinWithSelect($query, $table, $one, $operatorOrColumns, $two, $type = "left", $where = false, $columns = array())

RelationCountTrait

Enables to count a related models. In future will prepare better docs.

Example

Usage of where:

$count = $model->relationCountWithWhere("user_permission", "user_id", $user, "App\\Models\\User");

Calling the function again will use the cache in relations array. After this call you can also use

$model->user_permission_{ForeignKey}_{userIdValueForWhere} which will the object of User model with count attribute.

You can also get the where index by passing variable which will be overided by the reference:

relationCountWithWhere($index, "user_id", $user, "App\\Models\\User");">
$index = "user_permission";
$model->relationCountWithWhere($index, "user_id", $user, "App\\Models\\User");

Simple call will return count and the index will be stored in $model->user

$model->relationCount("user", "App\\Models\\User") 
You might also like...
Laravel Ban simplify blocking and banning Eloquent models.
Laravel Ban simplify blocking and banning Eloquent models.

Laravel Ban Introduction Laravel Ban simplify management of Eloquent model's ban. Make any model bannable in a minutes! Use case is not limited to Use

Add Social Reactions to Laravel Eloquent Models. It lets people express how they feel about the content. Fully customizable Weighted Reaction System & Reaction Type System with Like, Dislike and any other custom emotion types. Do you react?
An Eloquent Way To Filter Laravel Models And Their Relationships

Eloquent Filter An Eloquent way to filter Eloquent Models and their relationships Introduction Lets say we want to return a list of users filtered by

ðŸ•ĩïļ Inspect Laravel Eloquent models to collect properties, relationships and more.

ðŸ•ĩïļ Eloquent Inspector Inspect Laravel Eloquent models to collect properties, relationships and more. Install Via Composer composer require cerbero/el

Laravel Nova Ban simplify blocking and banning Eloquent models.
Laravel Nova Ban simplify blocking and banning Eloquent models.

Laravel Nova Ban Introduction Behind the scenes cybercog/laravel-ban is used. Contents Installation Usage Prepare bannable model Prepare bannable mode

Use auto generated UUID slugs to identify and retrieve your Eloquent models.

Laravel Eloquent UUID slug Summary About Features Requirements Installation Examples Compatibility table Alternatives Tests About By default, when get

Record created by, updated by and deleted by on Eloquent models automatically.

quarks/laravel-auditors Record created by, updated by and deleted by (if SoftDeletes added) on Eloquent models automatically. Installation composer re

Observe (and react to) attribute changes made on Eloquent models.
Observe (and react to) attribute changes made on Eloquent models.

Laravel Attribute Observer Requirements PHP: 7.4+ Laravel: 7+ Installation You can install the package via composer: composer require alexstewartja/la

Eloquent Befriended brings social media-like features like following, blocking and filtering content based on following or blocked models.
Eloquent Befriended brings social media-like features like following, blocking and filtering content based on following or blocked models.

Laravel Befriended Eloquent Befriended brings social media-like features like following, blocking and filtering content based on following or blocked

Comments
  • Bump illuminate/database from 5.2.31 to 6.20.14

    Bump illuminate/database from 5.2.31 to 6.20.14

    Bumps illuminate/database from 5.2.31 to 6.20.14.

    Commits

    Dependabot compatibility score

    Dependabot will resolve any conflicts with this PR as long as you don't alter it yourself. You can also trigger a rebase manually by commenting @dependabot rebase.


    Dependabot commands and options

    You can trigger Dependabot actions by commenting on this PR:

    • @dependabot rebase will rebase this PR
    • @dependabot recreate will recreate this PR, overwriting any edits that have been made to it
    • @dependabot merge will merge this PR after your CI passes on it
    • @dependabot squash and merge will squash and merge this PR after your CI passes on it
    • @dependabot cancel merge will cancel a previously requested merge and block automerging
    • @dependabot reopen will reopen this PR if it is closed
    • @dependabot close will close this PR and stop Dependabot recreating it. You can achieve the same result by closing it manually
    • @dependabot ignore this major version will close this PR and stop Dependabot creating any more for this major version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this minor version will close this PR and stop Dependabot creating any more for this minor version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this dependency will close this PR and stop Dependabot creating any more for this dependency (unless you reopen the PR or upgrade to it yourself)
    • @dependabot use these labels will set the current labels as the default for future PRs for this repo and language
    • @dependabot use these reviewers will set the current reviewers as the default for future PRs for this repo and language
    • @dependabot use these assignees will set the current assignees as the default for future PRs for this repo and language
    • @dependabot use this milestone will set the current milestone as the default for future PRs for this repo and language

    You can disable automated security fix PRs for this repo from the Security Alerts page.

    dependencies 
    opened by dependabot[bot] 1
  • Bump illuminate/database from 5.2.31 to 6.20.12

    Bump illuminate/database from 5.2.31 to 6.20.12

    Bumps illuminate/database from 5.2.31 to 6.20.12.

    Commits

    Dependabot compatibility score

    Dependabot will resolve any conflicts with this PR as long as you don't alter it yourself. You can also trigger a rebase manually by commenting @dependabot rebase.


    Dependabot commands and options

    You can trigger Dependabot actions by commenting on this PR:

    • @dependabot rebase will rebase this PR
    • @dependabot recreate will recreate this PR, overwriting any edits that have been made to it
    • @dependabot merge will merge this PR after your CI passes on it
    • @dependabot squash and merge will squash and merge this PR after your CI passes on it
    • @dependabot cancel merge will cancel a previously requested merge and block automerging
    • @dependabot reopen will reopen this PR if it is closed
    • @dependabot close will close this PR and stop Dependabot recreating it. You can achieve the same result by closing it manually
    • @dependabot ignore this major version will close this PR and stop Dependabot creating any more for this major version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this minor version will close this PR and stop Dependabot creating any more for this minor version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this dependency will close this PR and stop Dependabot creating any more for this dependency (unless you reopen the PR or upgrade to it yourself)
    • @dependabot use these labels will set the current labels as the default for future PRs for this repo and language
    • @dependabot use these reviewers will set the current reviewers as the default for future PRs for this repo and language
    • @dependabot use these assignees will set the current assignees as the default for future PRs for this repo and language
    • @dependabot use this milestone will set the current milestone as the default for future PRs for this repo and language

    You can disable automated security fix PRs for this repo from the Security Alerts page.

    dependencies 
    opened by dependabot[bot] 1
  • Laravel 5.8 support

    Laravel 5.8 support

    Is your feature request related to a problem? Please describe. Add Laravel 5.8 support

    Describe the solution you'd like

    It appears that only one change needs to be done:

    BelongsTo getForeignKey & getOwnerKey Methods

    Likelihood Of Impact: Low

    The getForeignKey, getQualifiedForeignKey, and getOwnerKey methods of the BelongsTo relationship have been renamed to getForeignKeyName, getQualifiedForeignKeyName, and getOwnerKeyName respectively, making the method names consistent with the other relationships offered by Laravel.

    opened by pionl 1
  • Bump illuminate/database from 5.2.31 to 6.20.26

    Bump illuminate/database from 5.2.31 to 6.20.26

    Bumps illuminate/database from 5.2.31 to 6.20.26.

    Commits
    • 8445174 cast to int
    • da124fb Add more messages for detecting lost connection (happens during managed Postg...
    • df0f50a Use qualified column names in pivot query (#36720)
    • 07c17d1 Add WSREP communication link failure for lost connection detection (#36668)
    • a29e13b Add ssl broken pipe as lost connection error (#36601)
    • 99890e3 When using managed PostgreSQL instances on DigitalOcean every now and then th...
    • 00b016a formatting
    • fd2d667 Add limit bindings for having between + tests.
    • 7797c2a Update whereDay and whereYear to clean value.
    • c2d71ad Limit expected bindingx v2.
    • Additional commits viewable in compare view

    Dependabot compatibility score

    Dependabot will resolve any conflicts with this PR as long as you don't alter it yourself. You can also trigger a rebase manually by commenting @dependabot rebase.


    Dependabot commands and options

    You can trigger Dependabot actions by commenting on this PR:

    • @dependabot rebase will rebase this PR
    • @dependabot recreate will recreate this PR, overwriting any edits that have been made to it
    • @dependabot merge will merge this PR after your CI passes on it
    • @dependabot squash and merge will squash and merge this PR after your CI passes on it
    • @dependabot cancel merge will cancel a previously requested merge and block automerging
    • @dependabot reopen will reopen this PR if it is closed
    • @dependabot close will close this PR and stop Dependabot recreating it. You can achieve the same result by closing it manually
    • @dependabot ignore this major version will close this PR and stop Dependabot creating any more for this major version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this minor version will close this PR and stop Dependabot creating any more for this minor version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this dependency will close this PR and stop Dependabot creating any more for this dependency (unless you reopen the PR or upgrade to it yourself)
    • @dependabot use these labels will set the current labels as the default for future PRs for this repo and language
    • @dependabot use these reviewers will set the current reviewers as the default for future PRs for this repo and language
    • @dependabot use these assignees will set the current assignees as the default for future PRs for this repo and language
    • @dependabot use this milestone will set the current milestone as the default for future PRs for this repo and language

    You can disable automated security fix PRs for this repo from the Security Alerts page.

    dependencies 
    opened by dependabot[bot] 0
Releases(v1.4.2)
  • v1.4.2(Feb 11, 2022)

  • v1.4.1(Feb 10, 2022)

  • v1.4.0(Feb 10, 2022)

  • v1.3.3(Jan 8, 2020)

  • v1.3.2(Jan 3, 2020)

  • v1.3.1(Oct 7, 2019)

  • v1.3.0(Mar 21, 2019)

    Breaking change

    🎆 RelationJoinTrait will support custom where conditions defined in relation.

    You need to update your code if you are using all arguments

    modelJoin

    - modelJoin($query, $relationName, $operatorOrColumns, $type, $where , $columns)
    + modelJoin($query, $relationName, $operatorOrColumns, $type, $columns, $extendJoin)
    

    joinWithSelect

    - joinWithSelect($query, $table, $one, $operatorOrColumns, $two, $type, $where, $columns, $tableAlias)
    + joinWithSelect($query, $table, $one, $operatorOrColumns, $two, $type, $columns, $extendJoin, $tableAlias)
    
    Source code(tar.gz)
    Source code(zip)
  • v1.2.3(Mar 18, 2019)

    🎆 Add support for joining same tables but with different relation name

    Breaking change

    If you are using RelationJoinTrait and using joined table in where condition (using table name) you need to replace the table name to relation name (which is used for alias).

    Source code(tar.gz)
    Source code(zip)
  • v1.2.2(Nov 21, 2018)

  • v1.2.1(Oct 20, 2018)

  • v1.2.0(Jun 12, 2018)

    🎆 Add support for Laravel 5.4+

    Breaking change

    Laravel 5.3 and below is deprecated due HasManyOrOne relation change (getForeignKey is removed)

    Source code(tar.gz)
    Source code(zip)
  • v1.1.1(Jun 7, 2018)

  • v1.1.0(May 17, 2018)

    🙌 Added CleanHTMLFromAttributeTrait for removing HTML from attribute values 🛑 Breaking change: Properties naming has changed for NullEmptyStringAttributeTrait to $nullEmptyAttributes and $dontNullEmptyAttributes. Also now they can't be set via __construct method but only with by setting property in class public $dontNullEmptyAttributes = [];

    Source code(tar.gz)
    Source code(zip)
  • v1.0.2(May 20, 2016)

  • 1.0.1(May 18, 2016)

Owner
Martin Kluska
I make stuff (web, mobile, apps and ☕ïļ )
Martin Kluska
A small package for adding UUIDs to Eloquent models.

A small package for adding UUIDs to Eloquent models. Installation You can install the package via composer: composer require ryangjchandler/laravel-uu

Ryan Chandler 40 Jun 5, 2022
Tag support for Laravel Eloquent models - Taggable Trait

Laravel Taggable Trait This package is not meant to handle javascript or html in any way. This package handles database storage and read/writes only.

Rob 859 Dec 11, 2022
A simple drop-in solution for providing UUID support for the IDs of your Eloquent models.

Introduction A simple drop-in solution for providing UUID support for the IDs of your Eloquent models. Both v1 and v4 IDs are supported out of the box

GoldSpec Digital 501 Jan 4, 2023
A collection of useful traits for working with PHP 8.1 Enums

A library of helper traits for working with PHP 8.1 enums This package provides a series of traits that allows you to: RestorableFromName Trait Create

Mark Baker 24 Nov 24, 2022
Laravel package to search through multiple Eloquent models.

Laravel package to search through multiple Eloquent models. Supports sorting, pagination, scoped queries, eager load relationships and searching through single or multiple columns.

Protone Media 845 Jan 1, 2023
This package gives Eloquent models the ability to manage their friendships.

Laravel 5 Friendships This package gives Eloquent models the ability to manage their friendships. You can easily design a Facebook like Friend System.

Alex Kyriakidis 690 Nov 27, 2022
An opinionated package to create slugs for Eloquent models

Generate slugs when saving Eloquent models This package provides a trait that will generate a unique slug when saving any Eloquent model. $model = new

Spatie 1.1k Jan 4, 2023
A package to generate YouTube-like IDs for Eloquent models

Laravel Hashids This package provides a trait that will generate hashids when saving any Eloquent model. Hashids Hashids is a small package to generat

ΛÐģi 25 Aug 31, 2022
Collection of the Laravel/Eloquent Model classes that allows you to get data directly from a Magento 2 database.

Laragento LAravel MAgento Micro services Magento 2 has legacy code based on abandoned Zend Framework 1 with really ugly ORM on top of outdated Zend_DB

Egor Shitikov 87 Nov 26, 2022
An Eloquent Way To Filter Laravel Models And Their Relationships

Eloquent Filter An Eloquent way to filter Eloquent Models and their relationships Introduction Lets say we want to return a list of users filtered by

Eric Tucker 1.5k Jan 7, 2023