Overview
Author: Coder
Last Updated: 2023-09-11
It is important to have coding guidelines when working on a development team.
- It ensures everyone can easily read and understand since the code is formatted and organized.
- Helps eliminate confusion with inconsistencies when working on codebases.
- Who does not like looking at beautiful art all day?
Variable Naming
There are different cases to consider when naming variables.
- PHP Variables should be written in
snake_casesuch as$product_id - JavaScript Variables should be in
snake_caseas well, such asdata-product_idorvar product_id - Some legacy variables in JS such as
fieldsWrapperandbuttonsWrappershould be and are fine to leave ascamelCase - Variable names for class instantiations should be written in
PascalCasesuch as$MediaService = new MediaService(); - Variable names should be named in a way to identify the data. Variable names should not be super long.
Function Naming
There are different cases to consider when naming functions.
- Function names on Controllers should be written in
camelCase. Try to mirror Laravel's naming convention likestorePayment - Function names on Services should be written in
snake_caseexcept when mirroring an API like Strava that usescamelCase - Function names should be named in a way to identify the function. Function names should not be super long.
Code Formatting
Refer to VSCode Settings in the nav to automate on save.
- All code should be properly 4-space tabbed out
Single line commenting should be formatted with a space before the comment
// Permissions for Users 'view_users', 'add_users', 'edit_users', 'delete_users', // Users Route::get('/users/search', 'UserController@search'); Route::resource('users', 'UserController', ['except' => ['show']]);
Arrays
Keeping arrays organized and consistent makes it easier to manage.
- PHP should use
[]for arrays instead ofarray() - PHP arrays should have a trailing comma
$fields = [ 'first_name', 'last_name', ]; - JavaScript arrays should not have a trailing comma
var fields = ['first_name', 'last_name'];
HTML Form Builder
All new forms should be built with
spatie/html. If the package is missing, add it tocomposer.json.
- Refer to WebApps for assistance on building an HTML form quickly
- If you are copying a pre-existing form in
laravelcollective/htmlto another site that also haslaravelcollective/html, it's fine to not have to refactor tospatie/html - Please ensure to use proper structure, email type for email, phone_us class for phone
- Attribute fields lets stick with plural
attributes([])vs singleattribute()single ordata(). It will keep lines clean vs having an absurd amount of chains.
Form Building Quickly
Stop wasting time on building out forms. There is no need.
- List your fields for your table (I like to paste in Discord for reference)
# users id first_name last_name email password timestamps - Copy fields except id/timestamps into
Lines to Laravel Migration$table->string('first_name')->nullable(); $table->string('last_name')->nullable(); $table->string('email')->nullable(); $table->string('password')->nullable(); - Cleanup migration with proper syntax (Tool is to help quicken)
- Copy fields except id/timestamps into
Convert Lines to Model'first_name', 'last_name', 'email', 'password', - Paste above into your Model fillable
- Copy fields except id/timestamps into
Convert Lines to Laravel Request'first_name' => request('first_name'), 'last_name' => request('last_name'), 'email' => request('email'), 'password' => request('password'), - Paste into your create/update model call
(Optional/Helpful): Copy fields except id/timestamps into
Form Builder<div class="col-md-6"> <div class="form-group input-underline"> {{ html()->label('First Name', 'first_name')->class('mt-2') }} {{ html()->text('first_name')->class('form-control') }} <div class="underline"></div> </div> </div> <div class="col-md-6"> <div class="form-group input-underline"> {{ html()->label('Last Name', 'last_name')->class('mt-2') }} {{ html()->text('last_name')->class('form-control') }} <div class="underline"></div> </div> </div> <div class="col-md-6"> <div class="form-group input-underline"> {{ html()->label('Email', 'email')->class('mt-2') }} {{ html()->email('email')->class('form-control') }} <div class="underline"></div> </div> </div> <div class="col-md-6"> <div class="form-group input-underline"> {{ html()->label('Password', 'password')->class('mt-2') }} {{ html()->text('password')->class('form-control') }} <div class="underline"></div> </div> </div>
composer.json/package.json
The default layout for composer/package files are sorted in ABC when installing through CLI (the php package requirement line should be at top).
- Note: JSON does not have trailing commas
composer.json"require": { "php": "^8.2.0", "aws/aws-sdk-php-laravel": "3.*", "bacon/bacon-qr-code": "2.*" }package.json
"dependencies": { "@fortawesome/fontawesome-free": "6.*", "aos": "2.*", "bootbox": "6.*" }
Laravel Requests
Use Laravel's
request()helper.
- Allows you to set defaults
request('is_owner', '0') - Cleaner vs
$request->input('is_owner') ?? 0, would also need the $request variable instantiated too
Laravel Helpers
There are a lot of Laravel Helpers and ways to easily access them
// App Environment
app()->environment('production');
// Now
now()->parse($date)->format('m/d/Y');
now()->format('m/d/Y');
// String
str()->limit($string, 100);
str()->uuid();
// Auth and Guard
auth()->user();
auth('customer')->user();
Model Casts
Casts are required for structured model datasets.
/**
* Get the attributes that should be cast.
*
* @return array<string, string>
*/
protected function casts(): array
{
return [
'created_at' => 'date:m/d/Y',
'updated_at' => 'date:m/d/Y',
'reasons' => 'array',
'status' => 'boolean',
];
}
- Array: You can then pass and receive an array directly if your column in your migration was set to json
- Date: You can now receive a carbon object
$model->created_at?->format('m/d/Y')
Creating and Saving Models
There is a much simpler way to create and update models.
// Create QrCode
$qr_code = QrCode::create([
'user_id' => auth()->user()->id,
'company_id' => request('company_id'),
'type' => request('type'),
'description' => request('description'),
'data' => request('data'),
'uuid' => str()->uuid(),
]);
// Update QrCode
$qr_code->update([
'user_id' => auth()->user()->id,
'company_id' => request('company_id'),
'type' => request('type'),
'description' => request('description'),
'data' => request('data'),
]);
Laravel Collection Functions
Laravel Collection functions makes modifying datasets much easier.
You can wrap an array with collect function to turn it into a collection and call functions off of it
// Init Array $fruits = [['id' => 1, 'name' => 'Apple'], ['id' => 2, 'name' => 'Banana']]; // Pluck from Collection $fruits = collect($fruits)->pluck('name', 'id'); // Map to Groups from Collection $fruits = collect($fruits)->mapToGroups(function ($fruit) { return [$fruits['id'] => $fruit['name']]; }); // Implode from Collection $fruits = collect($fruits)->implode(',');- Object Casting
$fruit = (object)['id' => 1, 'name' => 'Apple'];
Refreshing Objects
It is important to call a fresh on a model if you plan on adding more attributes.
If you do not, the model might try to save later on in the code depending on what you are doing, causing an error.
$email_data = $user->fresh();
$email_data->test_user = true;
Laravel Relations and Attributes
Model relations and attributes come very helpful.
public function socialite_profile()
{
return $this->hasOne(SocialiteProfile::class);
}
public function getNameAttribute()
{
return $this->first_name . ' ' . $this->last_name;
}
public function getAvatarImageAttribute()
{
$avatar = asset('/assets/img/avatar.png');
if ($this->firstMedia('avatar')) {
$avatar = (new \App\Services\MediaService)->get_signed_url($this->firstMedia('avatar'));
}
return $avatar;
}
null Operators
It is important to null-check such as using
null coalescing,nullsafe, orternaryoperators.
Null coalescing operator
$user_id = $user_id ?? auth()->user()->id; $user_id ??= auth()->user()->id;Nullsafe operator
https://www.php.net/manual/en/language.oop5.basic.php#language.oop5.basic.nullsafe
$order->invoice?->number; $user->created_at?->format('m/d/Y');Ternary Operator
$has_invoice = ($order->invoice) ? true : false;
Laravel Markdown => HTML Emails
Default Laravel Email uses markdown as emails. This is not proper since markdown is for coders to make notes and write documentation, not to parse into HTML as emails.
- Refer to other codebases on HTML implementation for emails.
- Reasons
- Easily build and scale emails in beautifully HTML with beautifully tab-formatted templates
- Reduces and removes complexity of the horribly structured markdown emails
- Pass PDF files and attachments directly into email parser
- Only a single
General.phpclass is needed and allows padding a single template name to parse - Automatic email logging of
to_emails,cc_emails,bcc_emails,subject,title,template(class),email_template(blade), which logs very well without the need of additional Notification Controllers
Overriding Bootstrap
Do not override bootstrap classes directly.
Instead, create your own class or prefix it
.login .form-control{ } .form-login{ }
Git Commits and gitignore
It is important to review before you commit.
- Do NOT commit credentials
- Review your file changes before committing and do NOT commit files that should not be committed.
- Ensure to use the gitignore file on
Coding Cheat Sheetfor a good start to a good gitignore
Case Definitions
Understanding case definitions helps keep cases normalized through codebases.
snake_case
kebab-case
PascalCase
camelCase