Laravel Style Guide


Our Laravel Framework guide. In our best practices we aim to put together all the resources using the Laravel Framework.

  1. New Laravel Project Install
  2. Existing Laravel Project Clone
  3. General PHP Rules
  4. Configuration and view files
  5. Routing
  6. Controllers
  7. Blade Templates
  8. Comments

New Laravel Project Install

  1. Download and install Composer- Laravel utlilizes Composer to manage various dependancies. Hence it is important to have composer installed on your machine.

  2. Install Laravel to Composer- Laravel can be called and executed locally on your machine, by running composer global require "laravel/installer". This command creates a new directory allowing for fresh Laravel installs to be specified.

  3. Create new Laravel project- Composer will create a new project with the latest Laravel version currently i.e. 5.7 composer create-project laravel/laravel test

  4. Check to see whether the new project generated successfully then the following changes can be made-

    • php artisan key:generate (encrypt data such as sessions, passwords and tokens),
    • php artisan serve (generate new Local Development Server),
    • Laravel development server started: <http://127.0.0.1:8000>

Existing Laravel Project Clone

  1. Clone the project from GitHub- git clone project-directory-name

  2. Copy .env file on the root folder- If there hasn’t been an existing env file provided, run php artisan key:generate to generate a new .env file. Remember to change the DB_DATABASE, DB_USERNAME and DB_PASSWORD to correspond to your configuration.

  3. Database migrations- A database should have been provided, when the database has been provided or a new one has had to be made run php artisan migrate so that the latest changes to the database have been made.

  4. Check environment setup- By running php artisan serve the environment can be configured to see whether the installation was successful. If not it maybe worth running composer update in the project directory. Laravel development server started: <http://127.0.0.1:8000>

General PHP Rules

The formatting of our code must follow PSR-1 and PSR-2 where appropriate.

Configuration and view files

Configuration files and blade templates must use kebab-case.

config/
  contact-form.php

resources/
  views/
    thank-you.blade.php

Configuration keys must use snake_case.

// config/contact-form.php
return [
    'email_address' => env('PRIMARY_EMAIL_ADDRESS'),
];

Routing

All URLs should have a clear hierarchy:

https://wecreatedigital.co.uk/example
https://wecreatedigital.co.uk/example/example2
https://wecreatedigital.co.uk/example/example2/3
Route::get('example', 'ExampleController@example')->name('example'); // first-level
Route::get('example/example2', 'ExampleController@exampleTwo')->name('example2'); // second-level hierarchy
Route::get('example/example2/{id}', 'ExampleController@exampleThree')->name('example3'); // third-level hierarchy requiring a parameter
<a href="/example">
    Example 1, first-level hierarchy
</a>

<a href="/example/example2">
    Example 2, second-level hierarchy
</a>

<a href="/example/example2/{{ $id }}">
    Example 3, third-level hierarchy, must have parameter
</a>

Controllers

Where appropriate keep controllers simple and use CRUD keywords such as (index, create, store, show, edit, update, destroy). These methods can be automatically generated in the terminal by creating a new Resource Controller php artisan make:controller ExampleController --resource.

If you need other methods, it is best practice to create a new Controller, otherwise use the same formatting of the other functions. For example in the below, we could have ExampleController@exampleFunctionOne, and ExampleController@exampleFunctionTwo, or these functions could be separated an entirely separate file. Below is an example of additional methods besides the CRUD default:

class ExampleController
{
    // Default CRUD create function
    public function create()
    {
        // ...
    }

    // Find example Database record by id
    public function exampleFunctionOne($id)
    {
        $post = Post::find($id);

        return response(null, 200);
    }

    // Delete example Database record by id
    public function exampleFunctionTwo($id)
    {
        $post = Post::find($id)->delete();

        return response(null, 200);
    }
}

Here we fall back to default CRUD words, such as store and destroy:

class ExampletwoController
{
    // Create a new example Database record
    public function store(Request $request)
    {
        $post = new post;
        $post->name = $request->name;
        $post->content = $request->content;
        $post->save();

        return response(null, 200);
    }

    // Delete example Database record by id
    public function destroy($id)
    {
        $post = Post::find($id)->delete();

        return response(null, 200);
    }
}

Resource Controllers

Resource Controllers have default CRUD functionality as explained earlier, the routes for these functions can found through the terminal command php artisan route:list, in doing so, all routes in the application are listed. To target a Resource Route make sure the Form action/AJAX url matches. Below is an example of targeting some Resource Controller functions (More examples):

// Storing new Data to a Resource Controller
<form method="post" action="{{URL::route('example.store')}}">
	{{csrf_field()}}
</form>

// Deleting Data to a Resource Controller
$.ajax({
  type: 'DELETE',
  url: '/example/' + id,
  data: {
    "id": id
  },
});
// Register example Resource Controller routes
Route::resource('example', 'ExamplesController');

php artisan route:list result in terminal for Resource Controller routes:

| METHOD    | URL                    | NAME            | ACTION
|           |                        |                 |      
| POST      | example                | example.store   | App\Http\Controllers\ExampleController@store  
| GET       | example                | example.index   | App\Http\Controllers\ExampleController@index  
| GET       | example/create         | example.create  | App\Http\Controllers\ExampleController@create
| GET       | example/{example}      | example.show    | App\Http\Controllers\ExampleController@show   
| PUT       | example/{example}      | example.update  | App\Http\Controllers\ExampleController@update
| DELETE    | example/{example}      | example.destroy | App\Http\Controllers\ExampleController@destroy
| GET       | example/{example}/edit | example.edit    | App\Http\Controllers\ExampleController@edit   

Blade Templates

Indent using four spaces.

<a href="/contact-us">
    Contact Us
</a>

Don't add spaces after control structures.

@if($valid)
    Yay
@endif

Comments

If writing clear and concise code as outlined in this guidelines then comments should only assist the reading process:

// Always leave space before a single line

/*
 * Integer posuere erat a ante venenatis dapibus posuere velit aliquet
 * cras justo odio, dapibus ac facilisis in, egestas eget quam
 * aenean lacinia bibendum nulla sed consectetur
 */

For every method should be a comment explaining its use.