Smiley Happy Coder

SQLSTATE[HY000] [2002] Connection refused with SQLite in Laravel 5

I’ve come across this one a couple of times over the last few months, each time, I’ve managed to dig around and fix it but I thought for my own sanity I’ll write it down and where better than here.

The issue comes about when I’ve just started a new Laravel project. I’ve set up all the authentication etc and run my migrations to create the user tables etc.
Now when I try to register for the first time, I can’t create the user record.

Sanity Check

Just to make sure, before I make the big reveal, lets check a couple of things.

  1. Check the .env file to make sure you’re telling Laravel to use SQLite rather than MySQL which is the standard.
  2. Jump into the config/database.php file and ensure that the name of the database file is correct.
  3. Check the database file actually exists, if you have run some migrations you won’t have been able to get this far without the file being in place

So, out with it!

The big reveal I found was simply that I needed to restart php artisan serve. For some reason Artisan is perfectly able to talk to the database but the browser is not without a reload.
That is the part that utterly baffled me. Why was Artisan okay to migrate but the app cannot perform an INSERT.

So there we have it, I hope that helps someone else out there too!

  • Top

Upgrade Bootstrap to V4 in Laravel 5.5

I’m just starting a new Laravel project and I really wanted to get in on the Bootstrap 4 goodness. At the time of writing its still in beta so not really ready for production but whatever!

Installation

Pull down the package from NPM with the following command
Read On >

  • Top

Add Font Awesome to Laravel 5.5

I’ve just kicked off a new Laravel project and I really want to use some Font Awesome icons to dress it up a little.

So off I trot to their getting started page and, at the time of writing, there is no mention of installing using NPM.

I decided to do a little digging and found that there is indeed a package on NPM. So I set about installing it with the following command.

Install Font Awesome

npm install font-awesome --save-dev

Now all we need to do is to tell our app.scss to process this library

If you run Laravel Mix now things should all be peachy!

  • Top

An API caller repository called “Caller”

I spend a lot of time talking to API’s on various projects so some time ago I wrote a class to do the basic work for me.

Download Caller

The Class

<?php
 namespace App\Http\Repositories;
 use App;

 /**
  * Class File
  * @package App\Http\Repositories
  */
 class Caller
 {

/**
 * @var
 */
protected $api_host;

/**
 * @var
 */
protected $api_version;

/**
 * @var mixed
 */
protected $api_username;

/**
 * @var mixed
 */
protected $api_password;

/**
 * @var
 */
protected $path = null;

/**
 * @var
 */
public $status_code;
/**
 * @var
 */
public $result;

/**
 * Caller constructor.
 */
public function __construct ()
{
    $this->api_username = env('API_USERNAME');
    $this->api_password = env('API_PASSWORD');
    $this->api_host = env('API_HOST');
    $this->api_version = env('API_VERSION');
}

/**
 * setPath
 *
 * Method builds up the path to be used in the curl request.
 *
 * @param array $path
 */
public function setPath (array $path)
{
    $this->path = $this->api_host . 'v' . $this->api_version . '/' . $path['group'] . '/' . $path['route'];
}


/**
 * PerformGet
 *
 * Handle GET requests
 *
 * @return mixed
 */
public function performGet ()
{
    if ( is_null($this->path) ){
        exit('No path set, use setPath() method');
    }

    $this->perform();

}


/**
 * PerformPost
 *
 * Handle POST requests
 *
 * @return mixed
 */
public function performPost ( $data )
{
    if ( is_null($this->path) ){
        exit('No path set, use setPath() method');
    }

    $this->perform( 'post' , $data );

}

/**
 * Perform
 *
 * Method that actually performs the cURL command.
 *
 * @param null $method
 * @param null $data
 */
protected function perform($method = null , $data = null)
{
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $this->path);
    curl_setopt($ch, CURLOPT_TIMEOUT, 60); //timeout after 30 seconds
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
    curl_setopt($ch, CURLOPT_USERPWD, "$this->api_username:$this->api_password");

    if ( $method == 'post'){

        $fields_string = '';

        foreach($data as $key=>$value) {
            $fields_string .= $key.'='.$value.'&';
        }
        rtrim($fields_string, '&');

        curl_setopt($ch,CURLOPT_POST, count($data));
        curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string);
    }

    /*
     * Build the result and status code and return to object parameters
     */
    $result = curl_exec($ch);
    $status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);

    $this->status_code = $status_code;
    $this->result = $result;
  }
}

`

  • Top

Simple method to test if a key exists in a multidimensional array.

I’ve used this function/method a few times over the years so I thought I’d jot it down to save future me some headaches.

Sometimes I have needed to check an array to see if the key exists within it. One solution might be to just check if that key is set.

if ( isset( $array['key'])) {

The issue with this method is that I might not know what the key is called or even if it exists at the top level of the array. It could be a multidimensional array, it might not be.

So I wrote a wee function to help out. In this case I’m in a Laravel project so its a public static function in a Helpers repository.

You’ll see that the first thing that goes on is to check if the key exists at the top level of the array, if found the function will return. No sense battling on if we already have our answer.

The second thing I do is to loop over the items in the array and, should that item be an array, perform that same test and return, if nothing is found then return false.

I could have abstracted the ‘array_key_exists’ chunk off to a different method to dave duplication but I feel thats just a step too far.

/**
 * Simple method, pass a key then the array
 * Method will return a bool
 * 
 * @param $key
 * @param $array
 *
 * @return bool
 */
public function testIfKeyExistsInArray( $key , $array )
{
    if ( array_key_exists ($key, $array) ) {
        return true;
    }

    //If the item is an array, then dig into it...
    foreach( $array as $item ){
        if ( gettype($item) === 'array'){
            if ( array_key_exists($key , $item)){
                return true;
            }
        }
    }

    return false;
}

Example usage

if ( Helper::testIfKeyExistsInArray( 'add_another' , $request->all() )){
    //Do whatever here
}

Limitations

The isn’t a very intelligent method by any means, it literally just looks one level deep if the item is an array.

I’m 100% sure there are many many ways to skin this cat. But this does work.

  • Top

Running Laravel on a shared host, Ultimate guide!

Some time ago I wrote about running Laravel on a shared host and some tips and tricks for getting it running right.

Well recently I had cause to revisit the problem and get it running once again.

My server setup

When I create the new site, in my case it was a subdomain, on my server all I get is a folder. That’s it, a folder.

/subdomains/subdomain-name

Well as you can imagine this is pretty useless. Laravel like most PHP based systems these days keep their app type files above the public folder and rightly so in an ideal world. In my case I want it to work from the single folder.

Steps to take

  1. Redirect all traffic from the root folder to the public folder
  2. Include the subdomain-name/public/index.php from subdomain/index.php

Redirecting all traffic

Inside the root of the subdomain folder, so in my case /subdomains/subdomain-name I created a new .htaccess file with the following contents.

RewriteEngine On RewriteBase

RewriteCond %{THE_REQUEST} /public/([^\s?]*) [NC] RewriteRule ^ %1 [L,NE,R=302]

RewriteRule ^((?!public/).*)$ public/$1 [L,NC]

This simply redirect any traffic that comes in to the public/index.php

However there is an issue with this, it only works if there is a parameter passed for example the visitor has browsed to site.com/something If a visitor browses directly to the website then this won’t work! On to step 2…

Including the index file.

In the root folder open or create a file called index.php, inside that file paste the following code.

<?php

include_once('public/index.php');

This include then makes php act as if the request has indeed landed inside the public folder.

I hope this is of help to someone to get up and running with Laravel on a shared host.

  • Top

Tweet the highlighted text using Tweetbot and Keyboard Maestro

I have tinkered somewhat recently with Keyboard Maestro and in particular the ability to Tweet the highlighted text. I knew I could do this with Keyboard Maestro but it was a little bit of a learning process.

But why Tweet the highlighted text at all?

When I find something I like, a quote or a link to something interesting I’d quite like to easily post it. So I created my Tweet the highlighted text macro.

It looks like this Tweet the highlighted text

What does it do?

It quite simply performs a copy, to get the highlighted text into the clipboard. Then, similarly to my last macro, it opens Tweetbot and opens the new tweet dialogue. Once that’s open then Keyboard Maestro performs a paste.

One thing of note. I disabled the very last action which was to actually submit the Tweet. I found through using the macro that I often want to comment on the link so whatever.

Here’s a link to the macro on GitHub

  • Top

Getting HTML form data to PHP array

How many times have you built a HTML form that has an indefinite number of fields? Maybe a list of categories for example. Ultimately you want those in a PHP array so you can parse them later on. Well thankfully thats pretty gosh darned easy but its a nice little trick I picked up a while ago.

Lets imagine we have a list of fields where the user can enter a name for each category. You might have a button that when clicked a chunk of JavaScript will drop a new form input onto the end of the list.

Read On >

  • Top

Importing into MySQL using Source

I recently found the Source command for MySQL. When importing .sql files into MySQL the normal way would be to run the following command from outside of MySQL

mysql -u username -p databasename < filename.sql

This is a great command but sometimes the file size is just too large for this command to handle. I haven’t looked into why that is however, I have found a solution.

The Source Command

Source Command

This command appears to loop through the file line by line rather than try to import the whole file as one. However it works, works is the key work here 🙂

The Syntax

source /var/www/filename.sql

It is important to note that this is a MySQL command rather than a linux command which means you must already be logged into MySQL.

  • Top

Simple way to humanise files sizes in PHP

This is just a very quick post to show something I’ve just been working on.

I came upon the need to display file sizes in a human readable way. The PHP method FILESIZE returns the size of the file in bytes. You might see a file size of 1500 or even 23462966. Now what do that mean to the average user? Nothing, so lets humanise it.

The function to humanise files sizes

private function humaniseBytes($bytes , $precision = 2)
{
    //Get the length of the string
    $length = strlen($bytes);

    if ($length <= 3){
        return $bytes . 'B';
    } elseif( $length > 3 && $length < 7){
        return number_format($bytes / 1000 , $precision) . 'KB';
    } elseif( $length > 6 && $length <10 ){
        return number_format($bytes / 1000000 , $precision) . 'MB';
    } elseif ( $length > 9 && $length < 13){
        return number_format($bytes / 1000000000 , $precision) . 'GB';
    } elseif ( $length > 12){
        return number_format($bytes / 1000000000000 , $precision) . 'TB';
    }
}

The first thing you’ll note are the parameters passed, obviously the $bytes are passes as well as a variable called $precision. This variable just determines the decimal places that should be returned from the number_format function.

I then just simple loop through and find the length and divide by whatever I need to in order to move the decimal place correctly.

Some functions you might see calculate based on the actual file size, my method however uses the string length. Now I will say that this might not be the most accurate solution since a KB isn’t actually 1000 bytes but rather 1024 bytes.

I hope this helps someone out there.

  • Top

Post a new Tweet from anywhere via Tweetbot using Keyboard Maestro

I’ve long heard of all the great things that Keyboard Maestro can do. I’ve wanted to play with it for absolutely ages, so I started to tinker.

The first thing I decided to create was a method to post a new tweet from anywhere within the operative system. New tweet with tweetbot

So what does this workflow achieve?

We’ll put simply, to create a new tweet I have to work through a couple of steps.

  • Open Tweetbot
  • Click to the “New Tweet” button or menu item
  • Start typing
  • Click “Tweet” or type “Cmd” Return”

I don’t want to waste the time and in all honestly it prevents me from tweeting things because I just won’t move away from what I’m doing.

Often when I want to tweet it’s something that just crossed my mind. I don’t want to wander away from what I’m doing, I just want to post the Tweet as fast as I can.

My macro will, really quickly, switch to Tweetbot and open the new Tweet dialogue.

Heres what it looks like

New Tweet Macro

So, by typing “newtweet” absolutely anywhere within the operative system the macro is fired.

Link to macro on GitHub

  • Top

Prevent screen output from bash scripts

More recently I’ve been working on a few bash scripts that do repetitive tasks for me. One such script will build a new development web server and install various bits of software so that I can get working really fast. One of the things I dislike is the screen output of these scripts. It often looks like a massive mess and since I’ve been planning to release some of these scripts into the wild, a mess just wont do!

Screen Output

I read a lot about preventing screen output and I tested a lot of things I found but I think I’ve come across about the best solution. And let me just point out, its not, by any means, perfect.

I’ve talked before about piping command line outputs to different apps, for example my recent post on the Sublime Text command line tool

The best solution

It seems the best solution is to try to pipe the output to somewhere else. One solution I came up with was to pipe the screen output to a new file and then remove that file. But that feels somewhat hacky, however it does work.

The solution I have been using is to pipe the screen output to /dev/null So something like this.

git clone http://path-to-repository . | /dev/null

Since the path /dev/null doesn’t exist then nothing happens.

Caveat: I have found a few commands that seem to ignore this and just give the screen output regardless. As I said, its not perfect.

  • Top
--> -->