10.laravel Best Practice (Coding Standards Part 02) ? ?? ? - DEV Community
10.laravel Best Practice (Coding Standards Part 02) ? ?? ? - DEV Community
25 6
🧑🦰👩🦰
Laravel Best Practice [Coding Standards Part 02]
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.
Here You may see some Bad code which are used validator in controller.
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:us
'password' =>['required', 'string', new Password, 'confirmed']
])->validate();
return User::store($request->all());
}
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
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
//
];
}
}
02 Allow CSRF 👈
in authorize() function you need to change return as true .
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
/**
* 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:us
'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.",
];
}
}
function.
/**
* 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.
👈
02 Use Config, Constants, Language Files without
complexing code.
let's say you are adding users to database with number of status.
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.
CONST STATUS =[
"ApprovalPending"=>1,
"Approved"=>2,
"Declined"=>3,
"ReSubmitted"=>4,
];
Then you can use STATUS variable inside the switch case anywhere.
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;
}
03 Don't Execute Queries inside blade files. 👈
lot's of junior developers are doing this thing without looking about it.
This code is fine there no any issue. but let's look in to deep. This will execute 1001
queries for 1000 customers .
$customers = Customer::with('address')->get();
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.
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
lathindu1 / tutorials
Tutorials
Here I will show all the code blocks of my tutorials. you can copy anything or learn anything.
Articles
How To Connect Metamask With Laravel(Part 01 Connect And Make A Transaction) .
How To Connect Metamask With Laravel(Part 02 Validate Transactions) .
View on GitHub
GitHub Profile
lathindu1 / lathindu1
It's About Lathindu Pramuditha's Account
namespace App\Models
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Life;
Because .env files can be cached via php artisan config:cache and you
can't use env function after that. (it will return null)
So if any of the code uses env function, you can't config cache in the future.
great @bravemaster619 it's better to use config instep of env. and also we
can use both.
we can use real content inside config file and. if we have local only thing
we can use them inside .env .
like
"paypal_secret" = env("PAYPAL_SECRET" ,
'asdfthdnejs323jn23nk3jn2njk3n2'),
and for our sandbox in local we can use key's inside .env
PAYPAL_SECRET = "kjansjnaknjsnalhjsbljhslhjlhjsla"
This.
Using is worst thing you can do. You should always use
$request->all()
$request->validated() .
Great post! Well done! Awesome to see some high-quality Laravel content on
here!
Thanks man :)
Some comments may only be visible to logged-in visitors. Sign in to view all comments.
Lathindu Pramduitha
LOCATION
Sri Lanka
WORK
Founder, CEO At Axcertro
JOINED
Feb 9, 2021
DEV Community
🌚 Pro Tip
You can set dark mode, and make other customizations, by creating a DEV
account.
Sign up now