- Notifications
You must be signed in to change notification settings - Fork0
Laravel Hacks <> my personal and professional guide as a software developer
License
jdevfullstack-tutorials/laravel-hacks
Folders and files
Name | Name | Last commit message | Last commit date | |
---|---|---|---|---|
Repository files navigation
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
- Ignore The Platform Flag
- Unit & Integration Testing
- Safely Deleting A Module
- New Routes In Backend
- New Package Installation
- Adding New Column/s To A Table
- Database Interaction
- Deploying Laravel On Test / Production Servers
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.
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 thehtdocs
folder of XAMPP.
Another option is to simply download theproject from GitHub. But you don'tget the history of the project.
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.
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
https://laravel.com/docs/10.x/installation
After cloning a project,
composer install
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
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,
php artisan serve
and there you have it, enjoy coding !
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.
In modular approach, you need to tweak the defaultTestCase and the path so all modules will be tested,
then,
make sure that the
api_token
is updatedon the.env
file, it's needed for theaccess of the endpoints, else all test will simplyfail, if there is such authenticationphp artisan config:cache
php artisan test
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
writing Unit Tests makes you realize thateach function should do a task that can passor fail by testing it
allows you to make functions decoupled asmuch as possible
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.
usingnwidart/laravel-modules
,deleting a module should be handled correctly
php artisan module:disable your_module_name
php artisan cache:clear
- delete module directory manually
php artisan cache:clear
other developers that will pull these changeswill simply pull it and run
php artisan cache:clear
after pulling and when there are new routes in the backend,
php artisan route:cache
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.
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:
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
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,
we need to update the validationand sanitation code block
then finally, the Store & Update methods of the Controller
unit tests for the new column/s andfunctionality should be added too
In Laravel, it's best to use theLaravel Query Builder
and 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.
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.
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.
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.
There are so many ways to deploy Laravel, others evenhave the exact configuration for Laravel only.
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.
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.
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.
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.
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
Uh oh!
There was an error while loading.Please reload this page.
Stars
Watchers
Forks
Uh oh!
There was an error while loading.Please reload this page.