My attempt at creating an optional helper.

Laravels optional helper can be pretty useful. With its new optional closure you can do even more.

I wanted something similar in javascript so I wrote this based on my Laravel(ish) resource/transformer.

Image for post
Image for post

You can also provide a callback that will be called if the option exists.

Image for post
Image for post


My basic attempt at javascript data transformation, resources.js

Image for post
Image for post
check out the npm package, resources.js

We‘ve gone serverless at work and we’re using my favorite, nodejs! That means a lot of javascript.

I’ve been using callbacks to transform my results but I’ve become accustomed to Fractal and now Laravels own Eloquent Resources. I like having a “view layer” for my responses, it makes things a lot easier to modify months later.

I don’t need all the features, just basic transformation, so the script is pretty slim.

Resources are defined nearly the same as Laravel.

class UserResource extends Resource {
toArray() {
return {
id: Number(this.id),
name: this.name,
email: this.email,
posts: PostResource.collection(this.posts),
created_at: this.created_at,
updated_at: this.updated_at, …


Similar to Laravels Eloquent feature.

UPDATE: I’ve made this plugin a package.

npm install --save bookshelf-simplepaginate

Use the simplePaginate plugin to call a fetchAll and return single pages with meta data.

Intended for use with large datasets as pagination with counts can be slow.

Example:

bookshelf.plugin(require('./simplepaginate.plugin'));Model.where({ id: 1 }).simplePaginate({ page: 1 }).then(results => {
// results.data
// results.meta
});

Returns:

"data": [],
"meta": {
"pagination": {
"count": 1,
"per_page": 1,
"current_page": 0,
"links": {
"previous": null,
"next": null
}
}
}

Links are integers, not full links.


If you google around you’ll find plenty of examples on how-to create a custom authorizer for serverless lambda events.

I used this example when I was building mine:

// Return an IAM policy document for the current endpoint   
const effect = isAllowed ? 'Allow' : 'Deny';
const userId = user.username;
const authorizerContext = { user: JSON.stringify(user) };
const policyDocument = utils.buildIAMPolicy(userId, effect, event.methodArn, authorizerContext);

I ran into a couple issues after deploying and thought I might share them.

User is not authorized to access this resource

{
“Message”: “User is not authorized to access this resource”
}

After some debugging I noticed the error was not coming from my authorizer but from AWS itself and after redeploying it would go away. …


Image for post
Image for post

Step 1: Get a Server!

Image for post
Image for post

This example is written for Ubuntu 16.04.3 provided by DigitalOcean and ServerHub.

Provision a new droplet, vps, server, whatever you’re using and once you have the login details, login to SSH!

When you’re at the root terminal copy/paste the commands below to get everything configured.

Step 2: Add the PHP 7 Repositories

Run the following commands, as root, to install the PHP repositories to your sources.list, update apt-get and install.

add-apt-repository ppa:ondrej/php

If you’re missing add-apt-repository, like some plain systems are, install it and then add-apt-repository ppa:ondrej/php

apt-get install software-properties-common
apt-get install python-software-properties

then

apt-get update
apt-get -y install unzip zip nginx php7.2 php7.2-mysql php7.2-fpm php7.2-mbstring php7.2-xml …


We all use Laravels Validation feature to ensure we have the required input and it matches some sort of rule. The available rules cover plenty of situations but they fail to cover one of the most important rules, input Sanitization.

TL;DR

A typical validator

Laravels Auth system comes with a simple User model that provides validation of the users details before it’s inserted into your database. We see it like:

return Validator::make($data, [
'name' => 'required|max:255',
'email' => 'required|email|max:255|unique:users',
'password' => 'required|min:6|confirmed',
]);

These rules will ensure the data we need is there and of the desired length and type.

Image for post
Image for post

That’s it, we’re done! Nothing else to check, required and max made sure our data is safe, right? …


Laravels Soft Deleting allows you to retain deleted records in your database so they can be used or restored at a later point. Restoring deleted records is great if a mistake is made and you need to revert and retaining deleted data can often be useful in the event you need to pull up some old records.

TL:DR: Take me to the package!

Traditionally Deleting Relations

I’ve always used MySQL foreign key constraints to cascade delete related records. Laravel makes it easy to use foreign keys in migrations, set `onDelete` to cascade and walla, your relations will be deleted automatically.

But what happens when you enable SoftDeletes? Your database is never told to actually ‘delete’ a record, instead the `deleted_at` field is updated. So what happens to your cascading deletes? Nothing, your related records are left alone. …


UPDATE: There is a new version of this article.

Image for post
Image for post

Step 1: Get a Server!

Image for post
Image for post

UPDATE: Directions updated for Ubuntu 16.04 from DigitalOcean.

This example was originally written for Ubuntu 14.04.3 provided by DigitalOcean and ServerHub.

Provision a new droplet, vps, server, whatever you’re using and once you have the login details, login to SSH!

When you’re at the root terminal copy/paste the commands below to get everything configured

Step 2: Add the PHP 7 & NGINX 1.9.x Repositories

Run the following commands, as root, to install the PHP 7 and Nginx 1.9.x repositories to your sources.list, add the key, update apt-get and install.

add-apt-repository ppa:ondrej/php

If you’re missing add-apt-repository, like some plain systems are, install it and then add-apt-repository ppa:ondrej/php

apt-get install software-properties-common
apt-get install…


Image for post
Image for post

TL;DR: Check out the package.

I’ve been building an api for the past couple months and we’ve come to the point where the frontend needs to do some status checks. Status checks currently ping the crap out of the current api and are pretty darn slow.

The solution for us is a Socket based status check, the frontend connects, validates and performs checks as it sees fit.

There are many other reasons to use sockets in your web application, the most common example is a Chat server, but you can do almost anything with a Web Socket.

Ratchet?

“Ratchet is a loosely coupled PHP library providing developers with tools to create real time, bi-directionalapplications between clients and servers over WebSockets. This is not your Grandfather’s Internet.”


Image for post
Image for post

TL;DR: Check out the package.

I’ve been building an api for the past couple months and we’ve come to the point where the frontend needs to do some status checks. Status checks currently ping the crap out of the current api and are pretty darn slow.

The solution for us is a Socket based status check, the frontend connects, validates and performs checks as it sees fit.

There are many other reasons to use sockets in your web application, the most common example is a Chat server, but you can do almost anything with a Web Socket.

Ratchet?

“Ratchet is a loosely coupled PHP library providing developers with tools to create real time, bi-directionalapplications between clients and servers over WebSockets. This is not your Grandfather’s Internet.”

About

Will Bowman

Web Developer Since 1998

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store