Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Laravel Hacks <> my personal and professional guide as a software developer

License

NotificationsYou must be signed in to change notification settings

jdevfullstack-tutorials/laravel-hacks

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

5 Commits
 
 
 
 

Repository files navigation

Hits

Disclaimer : this is not a full Laravel tutorial.Rather, this is a collection of my most encounteredsituations, solutions and approaches. I'mdocumenting it because it's really hard tomemorize these things even if you do itevery single day and when returningto Laravel after a long break.

TOC

Initial Setup

Server Installation

Laravel has its own server when you run

php artisan serve

but that's not complete particularly whenyou need a database like MySQL, sowe need to install a development server.

On Windows OS for the local development environment,we need XAMPP. Go ahead and install it.

Cloning the Project

Most common way is togit clone.

If private, once you have access to the repo,you can clone it. If public, just clone it.

And make sure that it is inside thehtdocsfolder of XAMPP.

Another option is to simply download theproject from GitHub. But you don'tget the history of the project.

.env Config

Create a new text file name.env inside the root of the project.

Ask the concerned person for theexact content of the.env file if this is private.

If public, mostly it's theexample.env, so go aheadcopy the content of it and paste it on the actual.env.

Ever wonder why we don't include.env on GitHub ?

Because it tends to be different on differentmachines and usually contains sensitive data, likethe API token.

Composer & Artisan

Familiarity with the Composer and Artisan is needed.

composer - is a dependency management tool for PHP

artisan - this is the command line utility of Laravel

more on this here,

https://laravel.com/docs/10.x/installation

Installing & Running the Project

After cloning a project,

  1. composer install

  2. php artisan migrate:fresh --seed

when it's API and you have implementedthis

https://dev.to/grantholle/implementing-laravel-s-built-in-token-authentication-48cf

you need to run

  1. php artisan make:token

    copy paste the token on the frontend or any otherservice that will be needing it

then finally, the moment of truth,

  1. php artisan serve

and there you have it, enjoy coding !

Ignore The Platform Flag

If you run thecomposer install command and you get an error,temporarily we can use--ignore-platform-reqs to bypass the errorbut it's not a good practice. You need to identifywhat is causing the error.

For example, when we use an externalpackage QR Code, we need to enable GD Extension, henceeditphp.ini and uncommentextension=gd. Thentrycomposer install again.

This way we are installing the same versionsof the required packages.

Unit & Integration Testing

In modular approach, you need to tweak the defaultTestCase and the path so all modules will be tested,

then,

  1. make sure that theapi_token is updatedon the.env file, it's needed for theaccess of the endpoints, else all test will simplyfail, if there is such authentication

  2. php artisan config:cache

  3. php artisan test

Database Testing

This is very critical as all our tests, particularlybackend API will always have the database involved.

In my case, because I followed the genericauthentication and that token needs to be pastedso we can call the endpoints, I cannot useDatabase Migrations andRefreshDatabase, ratherwhat fits in my situation is Database Transactions

https://laravel.com/docs/5.4/database-testing#using-transactions

Why Unit Tests ?

  1. writing Unit Tests makes you realize thateach function should do a task that can passor fail by testing it

  2. allows you to make functions decoupled asmuch as possible

  3. it's a kind of regression testing where whenyou add new features to an existing system,you still are at least confident thatyou are not breaking the codebase by justrunning the unit tests and still passing them

As for me, the third reason is what I really likethe most, because that happens all the time,you just modify or add some new feature thenyou realize later on, other features are brokenbecause of that.

Safely Deleting A Module

usingnwidart/laravel-modules,deleting a module should be handled correctly

  1. php artisan module:disable your_module_name
  2. php artisan cache:clear
  3. delete module directory manually
  4. php artisan cache:clear

other developers that will pull these changeswill simply pull it and run

php artisan cache:clear

New Routes In Backend

after pulling and when there are new routes in the backend,

php artisan route:cache

New Package Installation

When a developer installed a new package locally,thecomposer.json &composer.lock will be updatedand this should be pushed to GitHubmain /master branch

This way, other developers will not install itthe way it was installed like

composer require ...

and we avoid merge conflicts in config filesand to keep the same package versions.

Other developers will just run

composer install

after pulling from GitHubmain /master branch.

Depending on the package, like if thereare modified files in theconfig directory,we need to run

php artisan config:cache

or

php artisan cache:clear

for the changes to take effect.

Adding New Column/s To A Table

If not yet having the actual data, developers havethe freedom to simply add new columns in the originalmigration file,

but this needs to be migrated as fresh

php artisan migrate:fresh

but we will be losing the data butsince it's not actual data, this isacceptable.

Otherwise having the actual data on production server,we must always create a new migration file

php artisan module:make-migration <add_new_column_to_table> ModuleName

and simply run

php artisan migrate

when pushed on GitHubmaster /main, other developers willsimply pull it and migrate too

and there are two conditions here:

  1. set column to nullable - updating the contentcan have problems in the future particularlyif there are existing data on the table, sodefault null to be safe

  2. column cannot be unique - if it's null andthere are existing rows that are null alsothen it's not unique anymore

after creating or editing the migration file,

  1. we need to update the validationand sanitation code block

  2. then finally, the Store & Update methods of the Controller

  3. unit tests for the new column/s andfunctionality should be added too

Database Interaction

Eloquent & Laravel Query Builder

In Laravel, it's best to use theLaravel Query Builderand theEloquent ORM. Why ?

First is because of security,namely SQL injection.

Second, this unifies the syntax whether, for example,you are using MySQL or PostgreSQL.

Joining Tables

I usually useLEFT JOIN in my queries. You canleft join more than two tables. Related tothis is the choice whether you use Natural Keyor Surrogate Key.

Surrogate Key or Natural Key

There is a tendency to use Natural Key as it hasmeaning and is straightforward. Also, you caneasily implement Searching / Filtering using this.

But if the Natural Key has the tendency tobe changed, then it's not ideal. It's a headacheactually. So, for the very first time, make surewhether a Natural Key will besubjected to change or not.

Database Normalization & Denormalization

If you will not be reaching 100k records or morethen it's sufficient to have up to 3rd Normal Form,otherwise, database structure will be too complex.Once reaching 3rd Normal Form, it's now timeto denormalize to lessen the number of tables.

Take note also that using purely Surrogate Keyviolates this, particularly the 3rd Normal Form.It has no relation to the actual table data.

Deploying Laravel on Test / Production Servers

There are so many ways to deploy Laravel, others evenhave the exact configuration for Laravel only.

Amazon EC2

But as for me, the best is Amazon EC2 because theway you install it remotely is like the way youinstall it locally, the only difference is thatmostly it's using Ubuntu whether it usesApache ornginx servers. So familiarity with Linux is needed.

WinSCP & PuTTY

To accessit remotely, we need WinSCP and it has PuTTY,an open-source terminal emulator.

If you know FTP, you will not find it difficultto use WinSCP, as it is an SFTP and FTP client for Windows.But not usually to transfer files particularly the code.For code, usegit pull to pull changes from GitHub.

For modifying server settings, because we are usingan FTP client, we can modify withoutusing the default for Linux, likesudo nano ... butrather opening files much like we open it on Notepad.

Git Pull or Manual File Transfer

Make sure that the files you are modifying are outsideyour project. If that is being tracked by Git and youchanged it, you can end up with merge conflicts. This willcause confusion also.

For all Git tracked files,modify it first in local then push to GitHub then pull toyour VM. If that is VM specific code and your local willbe affected, you can enclose it with a conditional, likeit will check whether theenv is production / test / local.

Different ENVs

Ever wonder why we have different environments ? Why, forexample, we cannot use on our local a production env or testenv ? Because it serves differently. For example, in localwe can simply runcomposer update without being bothered much.That's not the case in production setting. So you need a localenv to try things out.

As for the Test env, usually this has to do with testing.There is the test server that is usually being accessed bythe QA team. It's like a production setup but thedebug modeis on.

And finally the production environment, which does not havethe debug mode. Imagine returning the details of the serverand the errors / bugs. Well, you are giving thehackers the idea of the most vulnerable part of your system.

You don't update the production environment too, as thiscan ruin the entire production env. Imagine if you haveversion 1, and 2-3 functionalities of this are deprecatedbut your code is still using those functionalities thenyou upgraded to version 2, thenboom ... you just ruin your project.

Continuously Run Laravel On Test / Prod Env

When in Test / Production environments, weneed to run the application not with

php artisan serve

but rather usingpm2

https://pm2.io/docs/runtime/guide/installation/

and follow this

https://awangt.medium.com/run-and-monitor-laravel-queue-using-pm2-dc4924372e03

it can be alongside the frontend if that is separate buton the same VM.

About

Laravel Hacks <> my personal and professional guide as a software developer

Topics

Resources

License

Stars

Watchers

Forks


[8]ページ先頭

©2009-2025 Movatter.jp