DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’» is a community of 963,864 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

Create account Log in
Yogesh Galav
Yogesh Galav

Posted on • Updated on • Originally published at vue-technologies.com

Best Practice for Laravel Vuejs Application

This blog will guide you through best practices you need to follow for creating a great app in Laravel and vuejs. Best practices help other or new developers quickly grasp the app. Decreasing the time for knowledge transfer and increasing readability of code.

The reason I love Laravel is OOP with the most simple language ever (PHP). All the practices defined here are to keep the OOP Paradigm consistent.

Logic
1.)Try to avoid nested if else.
2.)Keep less and less code per function. Make more function for more logic.
3.)Don’t repeat the code more than 2 times. In the beginning , repeating is good to find commonness.

Indentation
In programming languages like python there are strict indentation rules but the same is not true for languages like php and js which make the code looks like shit even if it has best logic in it hence there are some standards set by the community and available for prettier code. It just makes the readability much better and readability is the second most important thing then logic.
I prefer the following extension in Vscode for code structuring

1.)Phpcs or php fixer or Php Intellisense.
Phpcs is the hard thing to install in vscode but there is no other option I was left with hence anyway I implemented it.
It has some unnecessary requirements like spaces in between statements and strictness which cannot be leveled down hence for beginning I would surely avoid it.

2.)ESLINT.
You can install the extension in vscode or install it via npm.

Naming
As the developer the most frustrating part of daily life is naming, to name each new variable, function, class we write. And we always run out of names somewhere like edit, update.
What would you name the function which sets the data for the edit part? Or retrieving the same data with a variety of other datas. You feel the pain right.

1.)Keep all the Route names in a small case separated by dash.
2.)Keep all the Folder names CamelCase.
3.)Keep the class name CamelCase.
4.)Keep the function name camelCase with the first letter small.
5.)Keep all local variable names in a small case, separated with underscore.
6.)Keep global variable names in all capital cases, separated with underscore.

The last point is given by the laravel community so if we all follow it, it will help all of us.
7.)Modal name should be singular and the table name should be plural.
8.)Keep the filename the same as the class.(PSR-2)

Laravel

Env
Along with all environment variables, env file is also helpful for keeping secret keys for services which are costing you. Because this is a file which has always been in gitignore.
Config
Keep all the programming constants which are not costing you inside the config directory. You can make files according to your own wish.
Route
With more complex applications you will find more and more routes and may find problems with traverse url->route->controller->function.
Well if you keep it sorted you will never need to traverse this path and reach the end directly.

Index route
Route::get(β€˜/items’, [ ItemController::class, β€˜index’]);

Show route
Route::get(β€˜/item/{item}’, [ ItemController::class, β€˜show’]);

Update route
Route::put(β€˜/item/{item}’, [ ItemController::class, β€˜update’]);

Delete route
Route::delete(β€˜/item/{item}’, [ ItemController::class, β€˜delete’]);

Don’t write any extra function if you want to get items for company or for user or filter or paginate. We will handle all that in the controller.
And writing array as second parameter with class will help you and your IDE directly jump to controller instead of finding it manually.

You can keep the master route for all Import Export if post variables are the same in all of them.

RouteServiceProvider
If you are tired of using findOrFail in each function you must use route binding.

FormRequest
Form Requests are the most lovely part of laravel as you can validate all the data by just defining the rules and it keeps the validation part separated from business logic. You may find difficulty in writing and testing withValidator function but at the end of the day it all looks good.

Controller
Here comes the most working guy of our application. People write all sorts of things inside controllers. After all, it's pure php. But as I said earlier, keeping functions small and seeing route patterns might confuse you.
Most of the developers end up with writing supportive functions inside Models or private function in controllers.

1.)Controller should only contain at max 4-5 functions index, show, update, delete.
2.)Controller function’s only job is to collect data and return either json or HTML.
3.)If you want to fetch complex data use a Query builder inside some Helper Class.
4.)Else if you want to use Eloquent right direct queries inside the controller.
5.)Don’t write try catch everywhere as it violates DRY rule and it’s difficult to cover inside the test.

I will explain the 3rd and 4th point a little more. For most applications I build the fetching part requires supportive functions like filtering, permissions, sorting. And sometimes it uses more then 4-5 tables from the database, Hence it becomes very complex to handle it via eloquent.
And why write eloquently if you can get all the data in one query.
And after all we would be debugging SQL so why not to write it initially.

You can separate your fetch queries easily in the form of multiple functions inside the helper class.

For the saving, updating and deleting part, It is more easy and readable to do so eloquently.
Even if an eloquent query is multiple lines and is repeated please repeat it.

Models
My last statement in the controller might confuse you but if you don’t want to end up with similar functions with the same job in model please do consider the following.

1.)Don’t return any data or query from a custom function inside the model.
2.)Only use Relationships, Getters, Setters, Scopes and boot functions inside the model.
3.)Use traits if you still wanna use some abstracted code.

For all other functionality like import, export, notification, jobs use separate files each containing a single class and extending some base class hence following OOP.

Vuejs

If you wanna see common folder structure for vuejs see NUXT.js
The folder structure must include Layouts, Components and Pages at top level and may also include Apis, Containers, Store, Utils and Shared.

1.)The Pages folder should contain subfolders denoting URL, so you can implement folder based routing in future via NUXT or vite-plugin-pages.
2.)All the common components should end up in the Components folder.
3.)Use Section tag as parent tag in all non-functional major components. It makes debugging via html more easier.
3.)Don’t use stores until you don’t need the same data in multiple components or State Management.
4.)Don’t use multiple api for fetching data in a single page. You would not be able to use the store or state management properly then. Most of the time the data is duplicated and components require related data on the same page. If a component requires independent data and is to be used at multiple places then separate api calls make sense.
4.)Import Apis from a separate file to keep them structured, this way you keep track of apis wrt to models. Other alternative is to put apis in separate stores for eg. Vuex actions.

Import User from β€˜@/Apis/User.js’;
User.login(loginData);
Enter fullscreen mode Exit fullscreen mode

5.) Use @ for most importing paths.
6.)Use only one blade file if you are using SPA.
7.)Use Dynamic import to reduce bundle size, Because site speed is an important factor.
8.)Use Laravel mix for extracting, versioning, browserSync and HMR when working with webpack.
9.)Use the same language file from resources/lang if you are using vue with laravel.
10.)If you are using SPA, you can also try Inertia to directly return the vue file from the controller removing the need of blade files in between. It will also help you to use routes on the server side removing the need of vue-router and continue using props.
11.)You can use "Vite" if you wanna save time in development and webpack bundle optimization.

I hope you enjoyed reading this.
Please give your love and support to my Github open source repositories.
And If you are stuck somewhere or need to outsource your project feel free to hire us.

Thank You and Have Nice Day!

Top comments (0)

🌚 Friends don't let friends browse without dark mode.

Sorry, it's true.