2017 © Pedro Peláez
 

library helpers-laravel

A collection of useful classes to help making Laravel applications easier

image

langleyfoxall/helpers-laravel

A collection of useful classes to help making Laravel applications easier

  • Wednesday, July 25, 2018
  • by langleyfoxall
  • Repository
  • 4 Watchers
  • 0 Stars
  • 25 Installations
  • PHP
  • 0 Dependents
  • 0 Suggesters
  • 0 Forks
  • 0 Open issues
  • 8 Versions
  • 2400 % Grown

The README.md

Helpers Laravel

Packagist, (*1)

A repository of Laravel specific helper classes to help standardise work. API helpers, converters etc., (*2)

Installation

The Langley Foxall Helpers Laravel package can be easily installed using Composer. Just run the following command from the root of your project., (*3)

composer require langleyfoxall/helpers-laravel

If you have never used the Composer dependency manager before, head to the Composer website for more information on how to get started., (*4)

Helpers

Models

The Models helper offers helpful functions to do with Eloquent Models., (*5)

Methods

All methods can be called statically., (*6)

all

Get a Collection of all models., (*7)

Example Usage
$collection_of_models = Models::all()
Key Details
Parameters None
Throws None
Returns Collection
utf8EncodeModel

Encodes attribute values of a single model to UTF-8, and returns the model., (*8)

Example Usage
$encoded_user = Models::utf8EncodeModels($user)
Key Details
Parameters Model
Throws None
Returns Model
utf8EncodeModels

Encodes attribute values of mutliple models to UTF-8, and returns a collection of model., (*9)

Example Usage
$collection_of_encoded_users = Models::utf8EncodeModels($users)
Key Details
Parameters A Collection of Models
Throws None
Returns A Collection of Models
getColumns

Get an Array of the database columns for a given model., (*10)

Example Usage
$columns = Models::getColumns($user)
Key Details
Parameters Model
Throws None
Returns Array
getNextId

Get the next auto incremented ID for a model., (*11)

Example Usage
$next_id = Models::getNextId($user)
Key Details
Parameters Model
Throws Exception
Returns Integer
areRelated

Check if an unspecificed number of models are related to each other., (*12)

Example Usage

If an instance of Model is passed, then areRelated will attempt to get a plural then singular method from the model that can then be used by the previous model in the sequence to confirm that they are related. If an array is passed, it expects the first element to be an instance of Model and the second to be a string which is the relationship method, (*13)

A NotRelatedException is also provided to be used in an application., (*14)

$related = Models::areRelated($user, $post, [$comment, 'comments'])
Key Details
Parameters Mutliple Models or Mutliple Array
Throws Exception or InvalidArgumentException
Returns Boolean
randomByWeightedValue

Takes a collection of Model's and returns one based upon a weighted column. It can also take a maxCap to simulate higher odds., (*15)

It should be noted when passing a maxCap you should pass in a desired return value if none of the items in the models list were hit., (*16)

Example Usage
$prizes = Prizes::all();
$selectedPrize = Models::randomByWeightedValue($models, 'chance');
//returns a prize as if the 'chance' column related to {$chance}/10,000,000 - if none are hit it will return null.
$selectedPrize = Models::randomByWeightedValue('App\Models\Prize', 'chance', 10000000, null);
Key Details
Parameters A Collection of Models or a string representation of a Model, column, maxCap = null, ifLose = null
Throws None
Returns Model or an object

IsRelatedTo

The IsRelatedTo helper is a trait that allows quick and easy access to the areRelated method in the Models helper., (*17)

Methods

isRelatedTo

Check if a single model is related to the parent model., (*18)

Example usage
class User extends Model {
    use IsRelatedTo;
}

$related = $user->isRelatedTo($post)
Key Details
Parameters Model or Array
Returns Boolean

Enum

The Enum helper is a trait that provides helpers for dealing with enum classes., (*19)

Methods

all

Return an array of all values., (*20)

Example usage
class UserType
{
    use \LangleyFoxall\Helpers\Traits\Enum;

    const ADMIN = 'admin';
    const USER = 'user';
}

class User extends Eloquent
{
    public function getValidTypes()
    {
        return UserType::all();
    }
}
Key Details
Parameters
Returns Array
valid

Check if a provided value is a valid value of the enum class., (*21)

Example usage
class UserType
{
    use \LangleyFoxall\Helpers\Traits\Enum;

    const ADMIN = 'admin';
    const USER = 'user';
}

class User extends Eloquent
{
    public function setTypeAttribute(string $type)
    {
        if (!UserType::valid($type)) {
            throw new InvalidUserType;
        }

        $this->type = $type;
    }
}
Key Details
Parameters String
Returns Boolean

ApiResponse

The ApiResponse helper standardizes an API response. Always containing the same fields:, (*22)

Key Type Description
status Integer status is used for accessibility when the response cannot access the HTTP client, such as axios
success Boolean success is a boolean to signify that an operation was successful or not
error NULL, String or Array error is used to describe errors or warnings that have happened during the operation
data NULL or Array data should contain the main resource information
meta NULL or Array meta should contain extra resource information, such as other endpoints that can be used with the current resource

The ApiResponse helper also implements ArrayAccess which can be used to transform data easily. Example usage can be found here., (*23)

After building up the response, before returning it from a Controller, you must call json., (*24)

Methods

success

Create a successful response instance., (*25)

Example Usage

None of the parameters are required., (*26)

$api_response = ApiResponse::success($data, $meta, $status)
Key Details
Parameters data, meta, status
Returns ApiResponse
error

Create a unsuccessful response instance., (*27)

Example Usage

None of the parameters are required., (*28)

$api_response = ApiResponse::error($errors, $status)
Key Details
Parameters error, status
Returns ApiResponse
data

Set the data to be returned in the response., (*29)

Example Usage

None of the parameters are required., (*30)

$api_response->data($data)
Key Details
Parameters NULL or Array
Returns ApiResponse
meta

Set the meta to be returned in the response., (*31)

Example Usage

None of the parameters are required., (*32)

$api_response->meta($meta)
Key Details
Parameters NULL or Array
Returns ApiResponse
status

Set the response status code., (*33)

Example Usage
$api_response->status($status)
Key Details
Parameters Integer
Returns ApiResponse
json

Get the JSON response object, (*34)

Example Usage
$json_response = $api_response->json()
Key Details
Parameters None
Returns JsonResponse
cache

Cache the current ApiResponse data for use in a later request. By default if the cache currently has data in it the data will not be overwritten. Using forceOverwrite it can be overwritten, this defaults to false. cache must be called after data is set., (*35)

Example Usage

lifespan accepts an Integer value for the lifespan in minutes or a Carbon time when the cache will be cleared. cache must be an instantiated ResponseCache., (*36)

ApiResponse::success($data)->cache(1, $cache)->json();
Key Details
Parameters lifespan, cache, forceOverwrite (Optional)
Returns ApiResponse

Response

The Response helper should only be used if, for whatever reason, API endpoints use the same Controller methods as web URIs. This helper will check to see if the request is expecting JSON or not and return the right response., (*37)

Key Type Description
request Request request is used when it comes to deciding which response to return to the client
type String type is a string, "success" or "error", which will determine which API Response is returned
message NULL, String or String message is used for a redirect back with a session variable (web) or an error message (API)
data NULL or Array data should contain the main resource information
meta NULL or Array meta should contain extra resource information, such as other endpoints that can be used with the current resource
status Integer status is used for accessibility when the response cannot access the HTTP client, such as axios
uri String uri is used when wanting to redirect rather than back with a web response

Methods

None of the following methods can be called statically. When instansiating a new instance of Response a Request object is required., (*38)

success

Create a successful response., (*39)

Example Usage

None of the parameters are required., (*40)

$response = (new Response($request)->success($message, $data, $meta, $status)
Key Details
Parameters message, data, meta, status
Returns Response
error

Create a unsuccessful response., (*41)

Example Usage

None of the parameters are required., (*42)

$response = (new Response($request)->success($message, $status)
Key Details
Parameters message, status
Returns Response
type

Set the response type. While error and success are not aggressively checked the type will default to success if not error., (*43)

Example Usage
$response = (new Response($request)->success($type)
Key Details
Parameters type
Returns Response
message

Set the message to be displayed if an error occurs or a back is triggered., (*44)

Example Usage
$response = (new Response($request)->message($message)
Key Details
Parameters message
Returns Response
data

Set the data to be returned in an successful ApiResponse., (*45)

Example Usage

None of the parameters are required., (*46)

$response = (new Response($request)->data($data)
Key Details
Parameters data
Returns Response
meta

Set the meta to be returned in an successful ApiResponse., (*47)

Example Usage

None of the parameters are required., (*48)

$response = (new Response($request)->meta($meta)
Key Details
Parameters meta
Returns Response
status

Set the status to be returned in an ApiResponse. This will be overwritten if called before success or error., (*49)

Example Usage
$response = (new Response($request)->status($status)
Key Details
Parameters status
Returns Response
redirect

Set the redirect URI to be called rather than redirecting back., (*50)

Example Usage

None of the parameters are required., (*51)

$response = (new Response($request)->redirect($uri)
Key Details
Parameters uri
Returns Response
end

Return the expected response., (*52)

Example Usage
$expected_response = (new Response($request)->end()
Key Details
Parameters None
Returns RedirectResponse or JsonResponse

ResponseCache

The ResponseCache helper simplifies caching API Responses taking into account differing request parameters and user accounts. Unique caches are generated based on the request route, method, parameters and user., (*53)

Key Type Description
request Request The request that the cache will be for.
userSpecific Boolean userSpecific specifies if the response is cached for individual users or if all users share one cache. Important: Misuse of userSpecific can lead to massive inefficiencies and security flaws. If a response is the same for any user userSpecific should be set to false so that a new cache is not created for every user. If a response contains data pertaining to that user userSpecific should be set to true so that users do not receive someone else's cached data.
excludeParams (Optional) NULL or Array Since request parameters are likely to change the data generated a seperate cache is generated for different sets of parameters so that the correct data is returned. However some parameters do not change the data generated so a new cache does not need to be generated when they change. Adding these parameters to excludeParams will mean that they are ignored.

Methods

None of the following methods can be called statically., (*54)

hasData

Returns if the current cache has any data., (*55)

Example Usage
if($cache->hasData()){...
Key Details
Parameters None
Returns Boolean
getData

Returns the data currently in the cache, returns null if empty., (*56)

Example Usage
$data = $cache->getData();
Key Details
Parameters None
Returns Mixed
cacheData

Saves data to the cache. Any data currently in the cache will be overwritten/, (*57)

Example Usage

data can be any serializable data, lifespan can be minutes as an Integer or a Carbon time that the cache will expire at., (*58)

$cache->cacheData(["Hello" => "World"], Carbon:now()->addSeconds(4404));
Key Details
Parameters data, lifespan
Returns None
getKey

Returns the unique key for the cache generated based on the request path, method, parameters and user., (*59)

Example Usage
$key = $cache->getKey();
Key Details
Parameters None
Returns String
clear

Clears the data for the given cache., (*60)

Example Usage
$cache->clear();
Key Details
Parameters None
Returns None

Usage with ApiResponse

A cache can be created from anApiResponse automatically by using the cache function on it. It will only cache new data if the cache does not contain data. See documentation here., (*61)

Example Usage
$cache = new ResponseCache($request, false);

if($cache->hasData()){
    $data = $cache->getData();
}else{
    $data = computationallyExpensiveFunction();
}

return ApiResponse::success($data)->cache(1, $cache)->json();

IdentifiedByUUID

The IdentifiedByUUID trait allows you to easily use V4 UUIDs over incrementing primary keys., (*62)

Example Usage

Change your migrations to allow the use of a UUID., (*63)

public function up()
{
    Schema::create('demos', function (Blueprint $table) {
        $table->uuid('id')->primary();
        $table->timestamps();
    });
}

Use the trait., (*64)

class Demo extends Model
{
    use IdentifiedByUUID;
}

Now when the model is saved, it will automatically be populated with a V4 UUID., (*65)

The Versions

25/07 2018

dev-master

9999999-dev https://github.com/LFSoftware/helpers-laravel

A collection of useful classes to help making Laravel applications easier

  Sources   Download

MIT LGPL-3.0-only

The Requires

 

The Development Requires

by Jordan Hall
by Dexter Marks-Barber
by Jared Wheatley

laravel helpers php

25/07 2018

1.2.0

1.2.0.0 https://github.com/LFSoftware/helpers-laravel

A collection of useful classes to help making Laravel applications easier

  Sources   Download

LGPL-3.0-only

The Requires

 

by Jordan Hall
by Dexter Marks-Barber
by Jared Wheatley

laravel helpers php

25/07 2018

dev-models-class

dev-models-class https://github.com/LFSoftware/helpers-laravel

A collection of useful classes to help making Laravel applications easier

  Sources   Download

LGPL-3.0-only

The Requires

 

by Jordan Hall
by Dexter Marks-Barber
by Jared Wheatley

laravel helpers php

13/07 2018

1.1.2

1.1.2.0 https://github.com/LFSoftware/helpers-laravel

A collection of useful classes to help making Laravel applications easier

  Sources   Download

LGPL-3.0

The Requires

  • php ^7.0.0

 

The Development Requires

by Dexter Marks-Barber
by Jared Wheatley

laravel helpers php

02/07 2018

1.1.1

1.1.1.0 https://github.com/LFSoftware/helpers-laravel

A collection of useful classes to help making Laravel applications easier

  Sources   Download

MIT

The Requires

  • php ^7.1.3

 

The Development Requires

by Dexter Marks-Barber
by Jared Wheatley

laravel helpers php

29/06 2018

1.1.0

1.1.0.0 https://github.com/LFSoftware/helpers-laravel

A collection of useful classes to help making Laravel applications easier

  Sources   Download

MIT

The Requires

  • php ^7.1.3

 

The Development Requires

by Dexter Marks-Barber
by Jared Wheatley

laravel helpers php

24/05 2018

1.0.0.x-dev

1.0.0.9999999-dev https://github.com/LFSoftware/helpers-laravel

A collection of useful classes to help making Laravel applications easier

  Sources   Download

MIT

The Requires

  • php ^7.1.3

 

The Development Requires

by Dexter Marks-Barber
by Jared Wheatley

laravel helpers php

24/05 2018

1.0.0

1.0.0.0 https://github.com/LFSoftware/helpers-laravel

A collection of useful classes to help making Laravel applications easier

  Sources   Download

MIT

The Requires

  • php ^7.1.3

 

The Development Requires

by Dexter Marks-Barber
by Jared Wheatley

laravel helpers php