Laravel share package

When building websites you most likely have social share buttons on your pages, adding them can be a repetitive task. This Laravel share package solves this issue.

After following the installation instructions you can add social share buttons to your page like this.

Share::page('http://blog.jorenvanhocht.be')->facebook();

You can generate one share link, but you can also generate all available services at once, just by chaining the service names.

Share::page('http://jorenvanhocht.be', 'Share title')
    ->facebook()
    ->twitter()
    ->googlePlus()
    ->linkedin('Extra linkedin summary can be passed here');

At the time of this writing the following services are available:

  • Facebook
  • Twitter
  • Google Plus
  • Linkedin

The source code can be found on Github and the package is installable through composer.

Recursively check if value exits in array

The native in_array php function is very handy to check if a value exists in an array. But when you are working with multidimensional arrays it does not work anymore.

When you want to check if your value exists in the multidimensional array, you can use the following helper function to acomplish that.

<?php

/**
 * Enhancement for the native php function in_array.
 * It can now recursively check if a value exists
 * in a given array.
 *
 * @param $needle
 * @param $haystack
 * @param bool $strict
 * @return bool
 */
function in_array_r($needle, $haystack, $strict = false)
{
    foreach ($haystack as $item) {
        if (($strict ? $item === $needle : $item == $needle) || (is_array($item) && in_array_r($needle, $item, $strict))) {
            return true;
        }
    }

    return false;
}

?>

Source: http://stackoverflow.com/questions/4128323/in-array-and-multidimensional-array?answertab=active#tab-top

Reseted password in Laravel not working

I had a pretty tough bug  to debug today, my reseted password using the Laravel resets password trait was not working. After some research I was able to define what was causing this bug and how I could resolve it.

If you are like me you would probably have set a mutator on your user model that Hashes the password before saving it in the database.

public function setPasswordAttribute($password)
{
    $this->attributes['password'] = Hash::make($password);
}

Now when you look in the ResetsPassword trait you will see that Laravel also hashes the new password. So the password was hashed twice, that’s why the new password was not working.

protected function resetPassword($user, $password)
{
    $user->forceFill([
        'password' => bcrypt($password),
        'remember_token' => Str::random(60),
    ])->save();

    Auth::guard($this->getGuard())->login($user);
}

Since I was not using the dafault Laravel Trait anyway (due to some custom stuff) I could just remove the bcrypt function in my controller. Now I was able to login again. If you are using the default Trait you will have to find another work around or remove your mutator.

If you are using the default Trait you will have to find another work around or remove your mutator.

Adding Mandrill tags to your Laravel email

The problem

When using Laravel mail with Mandrill as the mail driver you can send mails the Laravel way, just by adding the API key to your env file.

It works great but what if you use one Mandrill account for all your clients and you have to keep track of the number of emails send for each client?

API keys

The first thing coming to your mind will probably be to create an API key for each client. Which is great to see the difference in your outbound dashboard in Mandrill.

But using these api keys does not allow you to see how many emails you have sent with it, therefore we will need tags.

Mandrill tags

Using tags within Mandrill allows you to see how many emails you have sent with that tag. Besides creating an api key for each client, you also create a tag for them.

Attaching Mandrill tags using Mail::send(…);

Mandrill has a powerful api to send mail templates where you can also specify those tags. But we don’t want to use that api, we want to use the build in Laravel mail functionality.

According to the following Mandrill docs  you can also send tags using http headers. That’s great since Laravel allows you to add additional headers to emails.

Eventually, you will end up with a mail function similar to the following one:

Mail::send('your-mail-viewl', [], function($message) {
    $message->to('info@example.com');
    $message->subject('Subjectline');
    $message->getSwiftMessage()
        ->getHeaders()
        ->addTextHeader('X-MC-Tags', 'my-laravel-tag', 'my-second-laravel-tag');
});

You can even add multiple tags just by separating them with a comma.

Bulk removing Slack files

Removing your Slack files when you’re out of storage can be a real pain in the ass and time consuming. When you are on the free plan it can be even harder because you only have 5GB of storage and you will have to that frequently.

You will have to remove your files file by file, but an article I came across last week changed this for me, it allowed me to remove 100 files at a time without losing my most recent files.

At work, we even created a Slash command for it, that everyone, on our team, can run at the moment we reached our storage limit.

The only thing you have to do to get this to work with a slash command is creating a token parameter for the script so that you can use the same script for multiple users.

import requests
import json
import calendar
import argparse
from datetime import datetime, timedelta

parser = argparse.ArgumentParser()
parser.add_argument("token")
args = parser.parse_args()

_token = args.token
_domain = "thesedays"

if __name__ == '__main__':
    while 1:
        files_list_url = 'https://slack.com/api/files.list'
        date = str(calendar.timegm((datetime.now() + timedelta(-30))
            .utctimetuple()))
        data = {"token": _token, "ts_to": date}
        response = requests.post(files_list_url, data = data)
        if len(response.json()["files"]) == 0:
            break
        for f in response.json()["files"]:
            print "Deleting file " + f["name"] + "..."
            timestamp = str(calendar.timegm(datetime.now().utctimetuple()))
            delete_url = "https://" + _domain + ".slack.com/api/files.delete?t=" + timestamp
            requests.post(delete_url, data = {
                "token": _token, 
                "file": f["id"], 
                "set_active": "true", 
                "_attempts": "1"})
    print "DONE!"

Now when the slash command calls your API, you just run the Python script with the passed token. And the script starts deleting the files of the user who entered the command.

It already saved me a lot of time, big thanks to the original author of the script: Santiago L. Valdarrama

Return data from laravel events to controllers

Laravel events are lovely to work with, it makes your controllers much cleaner and it groups multiple tasks. For example, when creating a new user. I used it a lot but I never had to return data back to my controller.

At first, I was a bit worried, I had never seen an example where there was actually data returned to the controller.

But Laravel shouldn’t be Laravel if it was not possible, after a bit of research it seemed that you could just return whatever you want in every listener (in the handle method) of your event. In your controller, you would get an array with a key for each listener you have for the fired event.

# response of the fired event. This event had one listner 

0 => "{"slug":"my-slug","id":1634,"name":"my name","scmId":"git","state":"AVAILABLE","statusMessage":"Available","forkable":true,"project":{"key":"XXX","id":123,"name":"Jorenvh","description":"Joren Van Hocht","public":false,"type":"NORMAL","links":{"self":[{"href":"http://github.com/jorenvh"}]}},"public":false,"links":{"clone":[{"href":"http://github.com/jorenvh/blogify.git","name":"http"},{"href":"ssh://git@github.com/jorenvh/blogify.git","name":"ssh"}],"self":[{"href":"http://github.com/jorenvh/blogify"}]}}"]

Each of these keys contain the JSON encoded data that you returned in the handle method of your listener.

Happy birthday Laravel

Five years ago today Taylor announced the first version of Laravel, Happy birthday Laravel.

I’m using Laravel for almost 2 years now and started my journey at version 4.2. Two versions later today the framework has changed a lot and I became a big enthusiast of it.

Many thanks to Taylor Otwell for making my life as a developer more enjoyable.

Automate Composer self-updates

At These Days, the company I work for, we deploy our projects to our dev & staging servers through Slack. We developed a application that takes api calls from Slack slash commands to deploy these projects.

So we don’t ssh manually that much anymore to these servers. It speeds up our workflow but we noticed that we didn’t ran composer self-update that often anymore.

A quick tip so you don’t have to worry about it anymore is to setup a cronjob, we run it every morning at 6 o’clock, that runs this command for us. So no need to worry about that anymore.

Scotch.io published a tutorial a few days ago where in they explain how you can do this for your servers. So I suggested you to check that post.

I’m also writing a more in depth post about our Slack deploy tool so be sure to come back to check out how and why we build this tool. I also gave a talk about our workflow at the March PHP Antwerp meetup.

Export php variables to javascript

Spatie, known for their Laravel packages, released a brand new package. Laravel blade javascript is a Blade directive to export PHP variables to Javascript.

But instead of exporting variables in the controller our package does it in the view.

Read the full article on Freek Van der Herten his blog. You can also find all the other Spatie packages on their website.

New migration and blade features coming to Laravel 5.3

Taylor Otwell announced two new features coming to Laravel 5.3 on twitter today.  You will be able to roll back one migration at a time and you will have access to the $loop variable in blade foreach loops.

Rolling back one migration at a time

This new feature will come in handy when one of your migrations fail for some reason. You will be able to use it this way:

php artisan migrate:rollback --step=1


Blade $loop variable

In blade foreach loops you will have access to a $loop variable, it will allow you to do things like this, but knowing Taylor there will be a lot more available.

@foreach($users as $user)
    @if($loop->first)
        <!-- First iterartion -->
    @endif
    
    @if($loop->last)
        <!-- Last iteration -->
    @endif
@endforeach


Code credits go to Taylor Otwell & Laravel php