langleyfoxall/helpers-laravel

A collection of useful classes to help making Laravel applications easier

v3.0.0 2024-07-01 08:18 UTC

README

Packagist

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

Installation

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

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.

Helpers

Models

The Models helper offers helpful functions to do with Eloquent Models.

Methods

All methods can be called statically.

all

Get a Collection of all models.

Example Usage
$collection_of_models = Models::all()
utf8EncodeModel

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

Example Usage
$encoded_user = Models::utf8EncodeModels($user)
utf8EncodeModels

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

Example Usage
$collection_of_encoded_users = Models::utf8EncodeModels($users)
getColumns

Get an Array of the database columns for a given model.

Example Usage
$columns = Models::getColumns($user)
getNextId

Get the next auto incremented ID for a model.

Example Usage
$next_id = Models::getNextId($user)
areRelated

Check if an unspecificed number of models are related to each other.

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

A NotRelatedException is also provided to be used in an application.

$related = Models::areRelated($user, $post, [$comment, 'comments'])
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.

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.

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);

IsRelatedTo

The IsRelatedTo helper is a trait that allows quick and easy access to the areRelated method in the Models helper.

Methods

isRelatedTo

Check if a single model is related to the parent model.

Example usage
class User extends Model {
    use IsRelatedTo;
}

$related = $user->isRelatedTo($post)

Enum

The Enum helper is a trait that provides helpers for dealing with enum classes.

Methods

all

Return an array of all values.

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();
    }
}
valid

Check if a provided value is a valid value of the enum class.

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;
    }
}

ApiResponse

The ApiResponse helper standardizes an API response. Always containing the same fields:

The ApiResponse helper also implements ArrayAccess which can be used to transform data easily. Example usage can be found here.

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

Methods

success

Create a successful response instance.

Example Usage

None of the parameters are required.

$api_response = ApiResponse::success($data, $meta, $status)
error

Create a unsuccessful response instance.

Example Usage

None of the parameters are required.

$api_response = ApiResponse::error($errors, $status)
data

Set the data to be returned in the response.

Example Usage

None of the parameters are required.

$api_response->data($data)
meta

Set the meta to be returned in the response.

Example Usage

None of the parameters are required.

$api_response->meta($meta)
status

Set the response status code.

Example Usage
$api_response->status($status)
json

Get the JSON response object

Example Usage
$json_response = $api_response->json()
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.

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.

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

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.

Methods

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

success

Create a successful response.

Example Usage

None of the parameters are required.

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

Create a unsuccessful response.

Example Usage

None of the parameters are required.

$response = (new Response($request)->success($message, $status)
type

Set the response type. While error and success are not aggressively checked the type will default to success if not error.

Example Usage
$response = (new Response($request)->success($type)
message

Set the message to be displayed if an error occurs or a back is triggered.

Example Usage
$response = (new Response($request)->message($message)
data

Set the data to be returned in an successful ApiResponse.

Example Usage

None of the parameters are required.

$response = (new Response($request)->data($data)
meta

Set the meta to be returned in an successful ApiResponse.

Example Usage

None of the parameters are required.

$response = (new Response($request)->meta($meta)
status

Set the status to be returned in an ApiResponse. This will be overwritten if called before success or error.

Example Usage
$response = (new Response($request)->status($status)
redirect

Set the redirect URI to be called rather than redirecting back.

Example Usage

None of the parameters are required.

$response = (new Response($request)->redirect($uri)
end

Return the expected response.

Example Usage
$expected_response = (new Response($request)->end()

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.

Methods

None of the following methods can be called statically.

hasData

Returns if the current cache has any data.

Example Usage
if($cache->hasData()){...
getData

Returns the data currently in the cache, returns null if empty.

Example Usage
$data = $cache->getData();
cacheData

Saves data to the cache. Any data currently in the cache will be overwritten/

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.

$cache->cacheData(["Hello" => "World"], Carbon:now()->addSeconds(4404));
getKey

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

Example Usage
$key = $cache->getKey();
clear

Clears the data for the given cache.

Example Usage
$cache->clear();

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.

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.

Example Usage

Change your migrations to allow the use of a UUID.

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

Use the trait.

class Demo extends Model
{
    use IdentifiedByUUID;
}

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