Category Archives: PHP

(PHP) Sort array of objects by property value

usort($myArray, function($a, $b)
    return strcmp($a->myPropery, $b->myPropery);

Sort by predefined order:

$predefinedOrder = array(1,5,2,6);

usort($arrayOfObjects, function ($a, $b) use ($predefinedOrder ) {

    $flipped = array_flip($predefinedOrder);
    $left = $flipped[$a->myPropery)];
    $right = $flipped[$b->myPropery)];
    return $left >= $right;

(PHP) Make Laravel migration to change table

Create migration in console:

php artisan make:migration add_mycolumn_to_mytable

Use Schema::table() to access existing table (instead of Schema::create() for creating new tables)

public function up()
    Schema::table('mytable', function($table) {

public function down()
    Schema::table('mytable', function($table) {

Then run migrations:

php artisan migrate

(PHP) Get a list of run database queries in Laravel

This is great if you want to see what queries are actually run when using Eloquent.

        // Get all querys run
        $queries = DB::getQueryLog(); 

        // If you want to sort them by time this works
        usort($queries, function ($a, $b) {
            return $a['time'] < $b['time'];

        // Print them on screen in a readable way
        echo '<pre>';
        echo '</pre>';

(PHP) Log Laravel execution time to console

Put this in app/start/global.php to get Laravels execution time to the browser console log.


$start = microtime(true);

App::finish(function() use ($start) {
    echo "<script>console.log('App finish: ".round((microtime(true) - $start) * 1000, 3)." ms')</script>";

This works with L5:

This page took {{ (microtime(true) - LARAVEL_START) }} seconds to render

(PHP) Allow any delimiter in CSV file

In a Laravel app I made the users would upload CSV files. The problem was that fgetcsv only allows a single delimiter character, and it needs to be defined.

The problem with that is that when a user exports a CSV from MS Excel – it could end up using a wide array of delimiters depending on the locality settings in windows.  It kind of sucks that MS won’t let the user choose this on export, but that’s how it is.

So I solved it the quick and easy way, by making a function that simply replaces any delimiter character to  my desired delimiter. (Note that the tab character is in double quotes, since it won’t be interpreted as tab otherwise):

     * Will replace a number of CSV delimiters to one specific character
     * @param $file     CSV file
    private function replaceDelimiters($file)
        // Delimiters to be replaced: pipe, comma, semicolon, caret, tabs
        $delimiters = array('|', ';', '^', "\t");
        $delimiter = ',';

        $str = file_get_contents($file);
        $str = str_replace($delimiters, $delimiter, $str);
        file_put_contents($file, $str);

(PHP) Eloquent doodles for Laravel

// Get model by primary key
$myModel = MyModel::find($id);

//Where can use short syntax for equal comparison.
$myModels = MyModel::where('someAttribute', '=', 'someValue')->get();
$myModels = MyModel::where('someAttribute', 'someValue')->get();

// Delete models
$affectedRows = MyModel::where('someAttribute', 'someValue')->delete();

// Select distinct
$distincts = MyModel::distinct()->select('someAttribute')->where('someAttribute', 'someValue')->get();

// Select with Limit and offset
$myModels = MyModel::limit(30)->get();
$myModels = MyModel::limit(30)->offset(30)->get();

Different ways of getting a single model and checking if it’s there.

// 1
$model= MyModel::where('someAttribute', $someValue)->get();

if (!$model->isEmpty()) {
    $firstModel= $model->first()

// 2
try {
    $model= MyModel::where('someAttribute', $someValue)->firstOrFail();
    // Do stuff with model
} catch (ErrorException $e) {
    // Do stuff if it doesn't exist.

// 3
$models = MyModel::where('someAttribute', $someValue)->get(); // Collection of models
$models = MyModel::where('someAttribute', $someValue)->first(); // Single model or null

if (count($models)) {
    //Collection: to get the first item
    //if you used first() just use the $models