Laravel Best Practice [Coding Standards Part 02] 🧑‍🦰👩‍🦰
Tags: laravel, beginners, php, codequality
Published: 2021-04-19 17:52:37

Hello friends, This is the **second** article of **Laravel coding standards** article series. 

If you didn't see the first article, I recommend to read it for best practice.

####Laravel Best Practice Article 01 => [Click Here To Open Article](https://dev.to/lathindu1/laravel-best-practice-coding-standards-part-01-304l)

![arraow](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/uhvobpcrgn8m83cpio5a.gif)
 

#Article 02: Principles should adhere.✊

Here I will talk about **some principles** which are developer **should follow**.

![pK-gMzy3meGp1rdP21xe1TUB9Dde408OFq4S](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/su6t2d5vzd2f6luhbipf.jpg)
 
##01 Don't Use Validations Inside Controller 👈

When I review my junior developer's code, I have seen there are bunch of validators in the controller. Some time they just google the issue and copy things from Stackowerflow  or some where and put in the code without investigating about it. so that's the main problem which I seen with them.

Here You may see some **Bad** code which are used **validator** in controller.
```PHP
    public function store(Request $request){
         Validator::make($request, [
            'first_name' => ['required', 'string', 'max:255'],
            'last_name' => ['required', 'string', 'max:255'],
            'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
            'password' =>['required', 'string', new Password, 'confirmed']
        ])->validate();
        return User::store($request->all());
    }
```

so this is not a correct way to put validator.
we should use Customer Request to handle Validators.

######01 Create Custom Request. 👈

```BASH
php artisan make:request UserCreateRequest
```
above as a request name. you may use actual scenario . ex-: if you want to handle user update form request. You may create Request as **UserUpdateRequest**.

Once Created Request from the command. you can see **UserCreateRequest** inside your **project root -> app -> Http -> Requests** .

```PHP
<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class UserCreateRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return false;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            //
        ];
    }
}

```

In the class you may see two prebuilt functions called 
**authorize()** and **rules()** .

######02 Allow CSRF 👈

in **authorize()** function you need to change return as **true** .

otherwise your request will not work.

######03 Add Validation Rules. 👈

You can add validation methods inside **rules()** function.

```PHP
 public function rules()
    {
        return [
            'first_name' => ['required', 'string', 'max:255'],
            'last_name' => ['required', 'string', 'max:255'],
            'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
            'password' =>['required', 'string', new Password, 'confirmed']
        ];
    }

```

######04 Add Custom Validation Messages. 👈
Then you can add custom validation messages for every input, every validation methods. here you need to override **message()** function  from formRequest Trait.

and add messages by mentioning inputs and rules separating by dots. 

```PHP
    public function messages()
    {
        return [
            "first_name.required" => "User first name is required",
            "first_name.string" => "User first name type must be a string",
            "email.unique" => "This email is already used.",
        ];
    }
```

Finally **UserCreateRequest** may be like this.

```PHP
<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class UserCreateRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'first_name' => ['required', 'string', 'max:255'],
            'last_name' => ['required', 'string', 'max:255'],
            'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
            'password' =>['required', 'string', new Password, 'confirmed']
        ];
    }
    /**
     * Get custom messages for validator errors.
     *
     * @return array
     */
    public function messages()
    {
        return [
            "first_name.required" => "User first name is required",
            "first_name.string" => "User first name type must be a string",
            "email.unique" => "This email is already used.",
        ];
    }
}

```

Now You Can use **UserCreateRequest** inside controller  
function.

```PHP
   /**
     * Store Customer
     *
     * @param  UserCreateRequest $request
     * @return User
     */
    public function store(UserCreateRequest $request){
        return User::store($request->all());
    }

```

With this custom request you can have lot's of complex logics, rules inside it.


![images](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5vkm0psp0m81ohdeyruj.jpg)
 

##02 Use Config, Constants, Language Files without complexing code. 👈

let's say you are adding users to database with number of status.

like **ApprovalPending** , **Approved** , **Declined** , **ReSubmitted**

This the **Bad** way which lot's of juniors are doing.

```PHP

switch ($user->status) {
    case 1:
    // do the things for Pending status
        break;
    case 2:
    // do the things for Approved status
        break;
    case 3:
    // do the things for Declined status
        break;
    case 4:
    // do the things for Resubmitted status
        break;

}

```
above you may see if we changed integer for related status, we must change the switch function also for correct the status, and also if comments deleted by some how, you don't know what happened in case 1, what happened in case 2 like this.

to avoid this we can use Constant Variable which is defined inside related model.

```PHP

 CONST STATUS =[
        "ApprovalPending"=>1,
        "Approved"=>2,
        "Declined"=>3,
        "ReSubmitted"=>4,
    ];


```

Then you can use STATUS variable inside the switch case anywhere.

```PHP

switch ($user->status) {
    case User::STATUS['ApprovalPending']:
    // do the things for Pending status
        break;
    case User::STATUS['Approved']:
    // do the things for Approved status
        break;
    case User::STATUS['Declined']:
    // do the things for Declined status
        break;
    case User::STATUS['ReSubmitted']:
    // do the things for Resubmitted status
        break;
}

```
      
![identify_sqlitebrowser](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/l4xif2pxe28ue6lmanv2.png)
 

##03 Don't Execute Queries inside blade files. 👈

lot's of junior developers are doing this thing without looking about it.

```PHP

@foreach (Customer::all() as $customer)
    {{ $customer->address->street_address }}
@endforeach

```

This code is fine there no any issue. but let's look in to deep. This will execute **1001 queries** for **1000 customers** .

```PHP

$customers = Customer::with('address')->get();

@foreach ($customers as $customer)
    {{ $customer->address->street_address }}
@endforeach

```

This is perfect. This will execute only **2 queries** for **1000 of customers** . 


Above I talked about 3 main issues which junior developers are doing mostly.

I hope you find my post useful! Any feedback is greatly appreciated!

##You may Find my Upwork Profile Here.

[https://www.upwork.com/freelancers/lathindu](https://www.upwork.com/freelancers/lathindu)

below I mentioned my other articles. you may also read them.


#Other Articles 👈👈👈

- Laravel Best Practice [Coding Standards Part 01 ](https://dev.to/lathindu1/laravel-best-practice-coding-standards-part-01-304l)

- MetaMask Integration With Laravel Part2 [Click Here](https://dev.to/lathindu1/validate-metamask-transactions-with-etherscan-metamask-integration-with-laravel-part-2-25h6)

- MetaMask Integration With Laravel Part1 [Click Here](https://dev.to/lathindu1/metamask-integration-with-laravel-4mng)

Here I'm Adding Public GitHub Repository which will store all of my tutorials. you may clone it and see every tutorials what I will publish 🤗.

**GitHub Repository** {% github lathindu1/tutorials %}

**Thank You Very much**.
--Lathindu Pramuditha--


**GitHub Profile** {% github lathindu1/lathindu1 %}

![Screenshot 2021-04-19 at 23.08.02](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3q4lvrbmuupxu6o6pgx9.png)