Tag: PHP

  • 📂

    Migrating my website to Statamic

    I love Laravel.

    I also really like WordPress, for what it is. So when it came to originally putting my personal site together I just wanted to get a simple WordPress site together.

    I have attempted to build my own website and blog in Laravel from scratch multiple times over the years. I even stuck with a build for a while but ultimately went back to WordPress.

    My issue was only down to the fact that I wanted to write more in my own time and found I spent most my time tinkering.

    But I really love Laravel.

    So imagine my joy when I came across Statamic. Statamic is a CMS package that can be installed into a Laravel site and just works seamlessly alongside you Laravel code.

    I am in the process of rebuilding my personal site and will be getting it live as soon as I can.

    I think I will migrate my current site to a new domain, something like “davidpeach.me”, and then use the 4042302 technique to ensure my old posts are still found as I migrate the posts over.

    I’m really looking forward to getting creative with Statamic and then layering on all of the excellent Laravel features as a way to learn as much, and refresh my mind, about my favourite framework.


  • 📂

    Updating PHP versions in Ubuntu 20.04

    For an older PHP project, I needed to install an older version of PHP. This is what I did to set that up.

    Installing a different PHP version

    sudo add-apt-repository ppa:ondrej/php
    sudo apt-get update
    sudo apt-get install -y php7.1

    Rebinding php to required version

    Some of these binds are probably not need. I think the main ones, at least for my use case, were php and phar.

    sudo update-alternatives --set php /usr/bin/php7.1
    sudo update-alternatives --set phar /usr/bin/phar7.1
    sudo update-alternatives --set phar.phar /usr/bin/phar.phar7.1
    sudo update-alternatives --set phpize /usr/bin/phpize7.1
    sudo update-alternatives --set php-config /usr/bin/php-config7.1

    For some reason the --set flag stopped working, so I had to use:

    sudo update-alternatives --config php
    sudo update-alternatives --config phar
    
    etc. And update each one with the terminal prompt options for each.

    p.s. If using PHP-FPM, you could also set up different server conf files and point the FPM path to the version you need. My need was just because I was using the command line in the older project.


  • 📂

    Finally got my site to use the roots wordpress structure. Composer dependency management and deployment with laravel forge. 🤓


  • 📂

    How to easily set a custom redirect in Laravel form requests

    In Laravel you can create custom request classes where you can house the validation for any given route. If that validation then fails, Laravel’s default action is to redirect the visitor back to the previous page. This is commonly used for when a form is submitted incorrectly – The visitor will be redirected back to said form to correct the errors. Sometimes, however, you may wish to redirect the visitor to a different location altogether.

    TL;DR (Too long; didn’t read)

    At the top of your custom request class, add one of the following protected properties and give it your required value. I have given example values to demonstrate:

    protected $redirect = '/custom-page'; // Any URL or path
    protected $redirectRoute = 'pages.custom-page'; // The named route of the page
    protected $redirectAction = 'PagesController@customPage'; // The controller action to use.
    

    This will then redirect your visitor to that location should they fail any of the validation checks within your custom form request class.

    Explaination

    When you create a request class through the Laravel artisan command, it will create one that extends the base Laravel class Illuminate\Foundation\Http\FormRequest. Within this class the three protected properties listed above are initialised from line 33, but not set to a value.

    Then further down the page of the base class, on line 127 at the time of writing, there is a protected method called getRedirectUrl. This method performs a series of checks for whether or not any of the three redirect properties have actually been set. The first one it finds to be set by you, in the order given above, is the one that will be used as the custom redirect location.

    Here is that getRedirectUrl method for your convenience:

    /**
    * Get the URL to redirect to on a validation error.
    *
    * @return string
    */
    protected function getRedirectUrl()
    {
        $url = $this->redirector->getUrlGenerator();
    
        if ($this->redirect) {
            return $url->to($this->redirect);
        } elseif ($this->redirectRoute) {
            return $url->route($this->redirectRoute);
        } elseif ($this->redirectAction) {
            return $url->action($this->redirectAction);
        }
    
        return $url->previous();
    }
    
    

    Do you have any extra tips to add to this? Let me know in the comments below.

    Thanks.


  • 📂

    Laravel Blade push and stack

    Laravel’s blade view compiler is second to none. I’ve used a couple of different templating engines and blade is by far my favourite.

    Including Partials

    The way in which we include partials of views within our main views is as follows:
    @include(‘partials.my-first-partial’)
    It will inject that partial’s content in the specified place.

    Defining Sections

    Within our views, we define “sections” with the following syntax:

    @section(‘section_name’)
    
        The section’s content within here
    
    @stop

    And we can define as many sections as we need for our project.

    When the same section is used in multiple places within one compilation

    Imagine we have master template file as such:

    // layouts.main.blade.php
    <!doctype html>
    
    ...
    @yield(‘partials.form’)
    ...
    
    @yield(‘custom_scripts’)
    
    

    Let’s suppose we have the following layout template that extends our main layout one and is including three partials. This example is a form template including its various inputs from separate partials. For my own website I have a different form for each of my post types and so I have the inputs in separate partials for easy reuse.

    // partials.form.blade.php
    @extends(‘layouts.main’)
    
    <form>@include(‘parials.form-title’)
    @include(‘parials.form-content’)
    @include(‘parials.form-tags’)</form>
    

    Let’s next suppose that in a couple of those partial input views you need to inject some custom scripting. This is a slightly contrived example, but it will illustrate the point.

    // partials.form-content.blade.php
    <textarea class="content" name="content"></textarea>
    
    @section(‘custom_scripts’)
    // dummy javascript as example
    $(‘.content’).doSomething();
    @stop
    
    // partials.form-tags.blade.php
    <select class="tags" name="tags">
    <option value="tagone">Tag One</option>
    <option value="tagtwo">Tag Two</option>
    <option value="tagthree">Tag Three</option>
    </select>
    
    @section(‘custom_scripts’)
    $(‘.tags’).doSomethingElse()
    @stop
    

    Now, when the form page gets compiled, only the first occurrence of the ‘custom_scripts’ section will be included.

    So what if you needed to be able to define this section in chunks across partials?

    Introducing Blade’s Push & Stack directives

    To give this functionality, Laravel does in fact have two little-known directives called ‘push’ and ‘stack’.

    They allow you to ‘stack up’ items across partials with the ‘push’ directive, which can then be echoed out together with the ‘stack’ directive.

    Here’s the above form example but with ‘push’ and ‘stack’ used in place of ‘section’ and ‘yield’.

    // layouts.main.blade.php
    <!doctype html>
    
    ...
    @yield(‘partials.form’)
    ...
    
    @stack(‘custom_scripts’)
    
    
    // partials.form-content.blade.php
    <textarea class="content" name="content"></textarea>
    
    @push(‘custom_scripts’)
    // dummy javascript as example
    $(‘.content’).doSomething();
    @endpush
    
    // partials.form-tags.blade.php
    <select class="tags" name="tags">
    <option value="tagone">Tag One</option>
    <option value="tagtwo">Tag Two</option>
    <option value="tagthree">Tag Three</option>
    </select>
    
    @push(‘custom_scripts’)
    $(‘.tags’).doSomethingElse()
    @endpush
    

    This will now compile all uses of the @push(‘custom_scripts’) and echo them out as one wherever you call @stack(‘custom_scripts’)

    When I was shown this technique by a mate at work, it blew my mind.

    Have fun.


  • 📂

    Bypassing Laravel’s CSRF Middleware on selected routes (from 5.1)

    Laravel does a great job at protecting us from cross-site request forgeries – or C.S.R.F. for short.But sometimes you may not wish to have that layer present. Well with Laravel 5.1 you can very easily bypass this middleware, simply by populating an array in the following file:

    app/Http/Middleware/VerifyCsrfToken.php

    Within this class you can add a protected property — an array — called $except, which will tell Laravel to use this middleware except for the ones you specify here.

    A complete example could be:

    protected $except = [
        'ignore/this/url',
        'this/one/too',
        'and/this',
    ];

    So for those three URLs, the CSRF middleware would be skipped.