Standing at your desk is known to have major health benefits. The Fidgity desk mat furthers that by giving your feet and legs comfort, exercise, and fidgeting opportunities. It’s made from anti-fatigue materials and has a 360º rotating platform, stretching wedges, deep-tissue massage balls, and a foot roller/balance bar.
Learn how to code in 2021 with training on the 12 most popular programming languages
https://ift.tt/3u8BVdt
The more dependent we become on apps, the more demand there’ll be for skilled programmers. It just so happens that learning how to code is easier than ever in 2021. In fact, we’ve rounded up 12 amazing deals on courses and training programs that will teach you the skills you need to start creating your own software, and they’re on sale for a limited time!
Learn Google Go – Golang Programming for Beginners
Go, or GoLang, is Google’s open-source programming language that’s designed to simplify many programming tasks. This course is perfect for beginners, as Go is one of the fastest-growing languages in the industry thanks to its ease of use and familiar syntax.
The Complete C# Programming Bundle: Lifetime Access
C# is an object-oriented programming language that’s incredibly popular for Windows, Android and iOS development, but it also finds its way into game design. This bundle comes with seven courses that will cover special features in C#, such as including pointers, header files and null-terminated strings. You’ll even learn how to build games in Unity.
If you want to specialize in Android development, then you shouldn’t overlook Kotlin. At the beginning of the course, you’ll learn programming fundamentals like variables, strings and collections, but you also find advanced content such as how to build a Slack clone and submitting your apps to the Google Play Store as you progress.
R isn’t particularly easy to learn, but it’s essential if you want to work in statistics or data analysis. These courses by bestselling Udemy instructor and data scientist, Minerva Singh, will show you how to use data science packages such as caret, tidyverse, dplyr and ggplot while working with data.
PHP is a hallmark language if you want to become a web developer. In fact, almost every website that you use is built on PHP. Here, you’ll learn how to set up your own server, create homepages and activate emails, create an R/L system and much more.
C++ can be hard to pick up, but doing so is worthwhile; you’ll find it in everything from server-side programming to game development, making it one of the most versatile languages you can learn. This bundle by software developer John Purcell features three C++ courses for students at a beginner, intermediate and advanced skill level, so you don’t need any prior experience in order to master this language.
The Complete 2021 Python Programming Certification Bundle
Python is growing in popularity due to its machine learning and deep learning applications, but it’s also widely used to create desktop apps and websites. These courses will teach you practical Python programming skills with hands-on projects such as building a name generator, neural networks and even data visualization apps.
Java is yet another in-demand language that’s used in practically every tech niche. This boot camp serves as a great introduction to Java as it covers concepts like inheritance, classes, flow control structures and more.
The Complete Ruby on Rails 6 Bootcamp Certification Bundle
Ruby isn’t as popular as some of the other languages on this list, but it’s incredibly easy to learn and is currently on the rise among web developers. Here, you’ll find five courses and over 42 hours of content ranging from Ruby on Rails fundamentals to building feature-rich applications from scratch.
The Complete MATLAB Programming Certification Bundle
MATLAB is quite different from the other languages featured here, as it’s primarily used to build programs that scientists and engineers use for data analysis. If you’re particularly interested in numerical computing and building algorithms, this seven-course bundle is for you.
Anyone who wants to build a successful mobile app empire should absolutely add Swift to their repertoire, and that’s exactly what you’ll learn in this bundle. You’ll discover Swift fundamentals such as using a declarative user interface and developing apps for everything from iPhones and iPads to Apple TV.
The Premium Learn to Code 2021 Certification Bundle
Not sure which language you should learn, or perhaps you want to be the master of all trades? This massive 27-course bundle offers lessons on just about every popular language you can think of.
Engadget is teaming up withStackSocial to bring you deals on the latest headphones, gadgets, tech toys, and tutorials. This post does not constitute editorial endorsement, and we earn a portion of all sales. If you have any questions about the products you see here or previous purchases, please contact StackSocial support here.
The Tailwind CSS team released a new free course – Tailwind CSS: From Zero to Production
https://ift.tt/3u7xn7d
The Tailwind CSS team released a brand new free course, Tailwind CSS: From Zero to Production, a new screencast series that teaches you everything you need to know to get up and running with Tailwind CSS v2.0 from scratch.
7 Underground Torrent Sites for Getting Uncensored Content
https://ift.tt/2NswW6T
Everyone loves Google and Bing, but normal search engines only brush the surface of the internet. To dive into the underground internet, you need to use underground search engines.
In many cases, these search engines are tapped into what is currently termed the invisible web, also known as the dark web. It contains information available on the internet that standard search engines don’t have access to because they are buried behind query forms or directory requests.
The following specialized underground search engines let you access all those hidden areas of the internet, like a legal torrent search engine or public records. Note that none of these can get you in trouble.
1. The Best Torrent Search Engines
If you aren’t familiar with torrents, it’s essentially a shared file that other nodes (computers) on the network can download. People access these networks using torrent clients like BitTorrent or uTorrent. Downloads take place in pieces so that even if you shut down your computer in the middle of a download, you can continue your download later.
With that said, finding available torrent files isn’t easy. To help, you can use a torrent search site like the ones on the list.
However, if you use any of the following popular torrent sites, you’ll have little trouble finding what you need.
Limetorrents is another one that’s been around for many years.
If you click on the Other or Browse links, you can sift through available torrent files (there are millions).
When you start browsing through the available torrent files, you’ll be surprised at the wide assortment of files available.
Torrent networks get a bad rap because of the illegal content you’ll find there, but you can also find useful things like free e-books, manuals, and other hard-to-find content.
There’s even an anime category!
RARBG [No Longer Available]
RARBG has been a favorite among torrent fans for some time. You can click on the Torrents tab to use the torrent search engine (or browse the list of new additions).
Or you can browse specific categories by clicking any of the links along the left side of the main page. You’ll also find a frequently updated top 10 list or read any recent torrent news.
Torrentz2
Torrentz2 has been around since around 2016 and sprung up when the original Torrentz site shut down. It’s what’s known as a "meta-search" engine, meaning that it scours through results from multiple torrent search engines so you don’t have to.
The main page touts over 61 million files in its database. So whether you’re looking to find something specific, or you’re just looking to browse, you’re likely to find what you want here.
Search results show you download size, user rating, and the estimated download time (based on the number of peers that are sharing).
AIO Search is another meta-search engine for torrent files.
What makes it unique is that you can select specific torrent search engines that you want to include.
The list of torrent sites this search engine plugs into is impressive. The results show up almost like an embedded web browser, with an individual tab showing search results from the individual torrent search engine.
You can also use it to search secret torrent search engines for images, videos, sub-titles, shared files, and even your favorite show.
Trulia has been around for many years now. It’s a real estate search engine that provides real estate information from various sources.
To get the best bargains, search in your desired neighborhood, and then click All For Sale from the menu. Choose Foreclosures.
If you prefer to avoid foreclosures, Trulia also shows recent price fluctuations up or down. This way you can jump on a good deal the moment a seller drops their price.
4. Public Records Search Engines
Another common search that isn’t easy to find are public records. Most public records search engines are disguised commercial companies trying to sell paid public records as search results to you.
The following search engines give you access to "secret" databases where you can search public records for free.
The Public Record Center is different. It’s more of an underground "portal" to government websites than a search engine.
However, it’s organized so well that it’ll save you a lot of time if you’re not sure where to go to find the public database.
Using the Public Record Center you can find government databases for court judgments and liens, conduct asset searches, and even look up copyright and trademark information.
This amazing little search engine digs through the institute’s extensive legal library and pulls out any information that you might need. This could include family law, criminal law, labor law and much more.
There are search engines buried throughout this excellent legal resource providing court opinion information, constitutional insights, and much more.
If you have any interest in law at all, take some time to check this one out.
The Mutual UFO Network (MUFON) is one of the nation’s central clearinghouses for UFO sightings.
MUFON investigators receive calls about sightings and then head out on field investigations. They then enter the information they gather into their reporting database.
This database is completely open to the public and searchable only through this case search form. Google has no idea any of these stories exist.
If you’re hungry for more, continue on by exploring our list of the best dark web websites online with TOR search engines. Just remember that once you head down the rabbit hole, there’s no turning back.
Livewire is a full-stack framework for Laravel that makes building dynamic interfaces simple, without leaving the comfort of Laravel. Livewire relies solely on AJAX requests to do all its server communications. Livewire completely sends Ajax requests to do all its server-side communication without writing any line of Ajax script.
In this blog, we have described a step-by-step guide for Creating CRUD (Create, Read, Update, Delete) Application in the Laravel 8 framework by using the Livewire package.
Table Of Contents
Create Laravel Application
Configure Database Details
Install Livewire Package
Create Model and Migration
Create Livewire Component and View
Define Routes
Run Project
Step 1: Create Laravel Application
First, open Terminal and run the following command to create a fresh laravel project:
-m this argument will create Migration in Single Command.
Now, Open migration file of category from database/migration and replace code in up() function:
public function up()
{
Schema::create('categories', function (Blueprint $table) {
$table->id();
$table->string('name')->nullable();
$table->text('description')->nullable();
$table->timestamps();
});
}
Migrate the database using the following command:
php artisan migrate
Now, Open Category.php model from app/Models and update code into Category.php Model:
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Category extends Model
{
use HasFactory;
protected $fillable = [
'name', 'description'
];
public $timestamps = true;
}
Step 5: Create Livewire Component and View
Run the below command to create a livewire view and component.
php artisan make:livewire category
After running this command you will find two files in the following path app/Http/Livewire/Contact.php and resources/views/livewire/contact.blade.php
Now, open app\Http\Livewire\Category.php and update the following code into that file:
namespace App\Http\Livewire;
use Livewire\Component;
use App\Models\Category as Categories;
class Category extends Component
{
public $categories, $name, $description, $category_id;
public $updateCategory = false;
protected $listeners = [
'deleteCategory'=>'destroy'
];
// Validation Rules
protected $rules = [
'name'=>'required',
'description'=>'required'
];
public function render()
{
$this->categories = Categories::select('id','name','description')->get();
return view('livewire.category');
}
public function resetFields(){
$this->name = '';
$this->description = '';
}
public function store(){
// Validate Form Request
$this->validate();
try{
// Create Category
Categories::create([
'name'=>$this->name,
'description'=>$this->description
]);
// Set Flash Message
session()->flash('success','Category Created Successfully!!');
// Reset Form Fields After Creating Category
$this->resetFields();
}catch(\Exception $e){
// Set Flash Message
session()->flash('error','Something goes wrong while creating category!!');
// Reset Form Fields After Creating Category
$this->resetFields();
}
}
public function edit($id){
$category = Categories::findOrFail($id);
$this->name = $category->name;
$this->description = $category->description;
$this->category_id = $category->id;
$this->updateCategory = true;
}
public function cancel()
{
$this->updateCategory = false;
$this->resetFields();
}
public function update(){
// Validate request
$this->validate();
try{
// Update category
Categories::find($this->category_id)->fill([
'name'=>$this->name,
'description'=>$this->description
])->save();
session()->flash('success','Category Updated Successfully!!');
$this->cancel();
}catch(\Exception $e){
session()->flash('error','Something goes wrong while updating category!!');
$this->cancel();
}
}
public function destroy($id){
try{
Categories::find($id)->delete();
session()->flash('success',"Category Deleted Successfully!!");
}catch(\Exception $e){
session()->flash('error',"Something goes wrong while deleting category!!");
}
}
}
Now, Create resources/views/home.blade.php and update the following code into that file:
With the rise of Mobile Development and JavaScript frameworks, using a RESTful API is the best option to build a single interface between your data and your client.
PHP has been the most popular web language in the present times by being simple to maintain, and quick to create feature-rich web applications. Websites that are dynamic, interactive, secure, and efficient need a powerful toolset to create and consume APIs.
In this article, you will learn how to build a modern RESTfulAPI in Laravel.
Now let’s look at building a PHP RESTful API with Laravel.
Table of Contents:
Prerequisites
Understanding Our Application
Setup New Laravel App
Create MySQL Database
Create Model and Migration
Create Controller and Request
Setup CRUD (Create, Read, Update and Delete)
Step 1: Prerequisites
Let’s look at these technologies as we build our API:
Step 2: Understanding Our Application
You will build a CRUD API. CRUD means Create, Read, Update, and Delete. Our API will have the following endpoints:
Method
URI
Name
Description
GET
api/posts
Index
All posts return.
GET
api/posts/{id}
Show
Detail of a particular post by ID.
POST
api/posts
Store
Create a new post.
PUT
api/posts/{id}
Update
Update a particular post by ID.
DELETE
api/posts/{id}
Destroy
Delete a particular post by ID.
Step 3: Setup New Laravel App
To get started, create a Laravel application. To do this, run the following command in your terminal:
composer create-project laravel/laravel rest-api
or, if you have installed the Laravel Installer as a global composer dependency:
laravel new rest-api
Next, start up the Laravel server if it’s not already running:
php artisan serve
You will visit your application on http://localhost:8000.
Step 4: Create MySQL Database
Create a new database for your application.
Login into MySQL and run the following command:
mysql -u<username> -p<password>
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 1791
Server version: 8.0.22-0ubuntu0.20.04.3 (Ubuntu)
Copyright (c) 2000, 2020, Oracle and/or its affiliates. All rights reserved.
Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
mysql>
For Create a new Database, run the following command:
CREATE DATABASE `rest-api`;
Step 5: Create Model and Migration
We can create a Model along with migration, run the following command:
php artisan make:model Post -m
-m this argument will create Migration in Single Command.
A new file named Post.php will be created in the app directory.
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
protected $table = 'posts';
protected $fillable = [
'name',
'image',
'description'
];
}
A migration file will be created in the database/migrations directory to generate the table in our database. Modify the migration file to create a column for name, description, and image, these all are fields that accept string value.
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreatePostsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('posts', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('image');
$table->text('description');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('posts');
}
}
Open the .env file and update the credentials to access your MySQL database:
Next, you will run your migration using the following command:
php artisan migrate
Step 6: Create Controller and Request
Create a resource Controller, run the following command:
php artisan make:controller PostController -r
Resourcecontrollers make it painless to build RESTful controllers around resources.
This is the initial content of PostController.php:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class PostController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
//
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
//
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
//
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
//
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit($id)
{
//
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
//
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
//
}
}
Next, create a Request file, run the following command:
php artisan make:request PostStoreRequest
As many of you already know, there are many ways to validate request in Laravel. Handling request validation is a very crucial part of any application. Laravel has some outstanding feature which deals with this very well. This is the initial content of PostStoreRequest.php:
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class PostStoreRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return false;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
//
];
}
}
HTTP Status Codes
We’ve also added the response()->json() call to our endpoints. This lets us explicitly return JSON data and send an HTTP code the client can parse. The most common codes you’ll be returning will be:
200 : OK. The standard success code and default option.
201: Created. Object created. Useful for the store actions.
204 : No Content. When the action was executed successfully, but there is no content to return.
206 : Partial Content. Useful when you have to return a paginated list of resources.
400 : Bad Request. The standard option for requests that cannot pass validation.
401 : Unauthorized. The user needs to be authenticated.
403 : Forbidden. The user is authenticated but does not have the permissions to perform an action.
404: Not Found. Laravel will return automatically when the resource is not found.
500 : Internal Server Error. Ideally, you will not be explicitly returning this, but if something unexpected breaks, this is what your user is going to receive.
503 : Service Unavailable. Pretty self-explanatory, but also another code that is not going to be returned explicitly by the application.
Step 7: Setup CRUD (Create, Read, Update and Delete)
1. Setup Routes
Note: All API requests will need the header Accept: application/json.
Add the routes to the API routes file, to access all the functions we wrote.
Now, open routes/api.php and update the following code into that file:
Now, open app\Http\Controllers\PostController.php and update the following code into that file:
2. Read All Post
For, get the list of all posts. Update the following code into that file:
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
// All Posts
$posts = Post::all();
// Return Json Response
return response()->json([
'posts' => $posts
],200);
}
Get the detail of the post by ID. Update the following code into that file:
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
// Post Detail
$post = Post::findOrFail($id);
if(!$post){
return response()->json([
'message'=>'Post Not Found.'
],404);
}
// Return Json Response
return response()->json([
'post' => $post
],200);
}
3. Create Post
Now, open app\Http\Requests\PostStoreRequest.php and update the following code into that file:
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class PostStoreRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
if(request()->isMethod('post')) {
return [
'name' => 'required|string|max:258',
'image' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
'description' => 'required|string'
];
} else {
return [
'name' => 'required|string|max:258',
'image' => 'nullable|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
'description' => 'required|string'
];
}
}
/**
* Custom message for validation
*
* @return array
*/
public function messages()
{
if(request()->isMethod('post')) {
return [
'name.required' => 'Name is required!',
'image.required' => 'Image is required!',
'description.required' => 'Descritpion is required!'
];
} else {
return [
'name.required' => 'Name is required!',
'description.required' => 'Descritpion is required!'
];
}
}
}
Now, open app\Http\Controllers\PostController.php and update the following code into that file:
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(PostStoreRequest $request)
{
try {
$imageName = Str::random(32).".".$request->image->getClientOriginalExtension();
// Create Post
Post::create([
'name' => $request->name,
'image' => $imageName,
'description' => $request->description
]);
// Save Image in Storage folder
Storage::disk('public')->put($imageName, file_get_contents($request->image));
// Return Json Response
return response()->json([
'message' => "Post successfully created."
],200);
} catch (\Exception $e) {
// Return Json Response
return response()->json([
'message' => "Something went really wrong!"
],500);
}
}
4. Update Post
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(PostStoreRequest $request, $id)
{
try {
// Find Post
$post = Post::findOrFail($id);
if(!$post){
return response()->json([
'message'=>'Post Not Found.'
],404);
}
$post->name = $request->name;
$post->description = $request->description;
if($request->image) {
// Public storage
$storage = Storage::disk('public');
// Old iamge delete
if($storage->exists($post->image))
$storage->delete($post->image);
// Image name
$imageName = Str::random(32).".".$request->image->getClientOriginalExtension();
$post->image = $imageName;
// Image save in public folder
$storage->put($imageName, file_get_contents($request->image));
}
// Update Post
$post->save();
// Return Json Response
return response()->json([
'message' => "Post successfully updated."
],200);
} catch (\Exception $e) {
// Return Json Response
return response()->json([
'message' => "Something went really wrong!"
],500);
}
}
5. Delete Post
Delete post by ID. Update the following code into that file:
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
// Post Detail
$post = Post::findOrFail($id);
if(!$post){
return response()->json([
'message'=>'Post Not Found.'
],404);
}
// Public storage
$storage = Storage::disk('public');
// Iamge delete
if($storage->exists($post->image))
$storage->delete($post->image);
// Delete Post
$post->delete();
// Return Json Response
return response()->json([
'message' => "Post successfully deleted."
],200);
}
You may or may not be aware that there is an artisan command to create the symbolic link from the storage folder to the public folder.
What it does is, it allows us to access the files. By default, laravel wants you to store your files in the storage directory keeping the public directory clean only for your public files.
This command helps us to generate symbolic links.
php artisan storage:link
It’d be a good idea to follow along with the simple demo app that can be found in this GitHub repo.
class VerifyUser implements ShouldQueue
{
private $user;
private $socialSecurityNumber;
public function __construct($user, $socialSecurityNumber)
{
$this->user = $user;
$this->socialSecurityNumber = $socialSecurityNumber;
}
}
When you dispatch this job, Laravel is going to serialize it so that it can be persisted in the queue store. Let’s take a look at how the final form will look like in the store:
Looking at the payload, you can see that the value of socialSecurityNumber is visible to the human eye. Any person—or program—that gains access to the queue store will be able to extract this value.
For most jobs this isn’t a problem. But if the job stores critical information in the payload, it’s better we encrypt it so that only our queue workers can read it while processing the job. To do that, we’ll need to implement the ShouldBeEncrypted interface:
use Illuminate\Contracts\Queue\ShouldBeEncrypted;
class VerifyUser implements ShouldQueue, ShouldBeEncrypted
{
private $user;
private $socialSecurityNumber;
public function __construct($user, $socialSecurityNumber)
{
$this->user = $user;
$this->socialSecurityNumber = $socialSecurityNumber;
}
}
This interface was introduced in Laravel v8.19.0 (Released on December 15, 2020)
The Ultimate Performance Checklist For Laravel Apps
https://ift.tt/3rI46Oo
Laravel is fast out-of-the-box, but you can make it faster if you optimize your configurations and application code. This guide lists a wide range of performance tips from quick wins to advanced techniques that would help you make your Laravel app the lean, mean machine your customers want.
The folks over at Enlightn helped us compile this guide. If you’re looking for an automated performance or security tool for Laravel, do check them out!
Why Performance?
We can all agree that we prefer an app that loads faster to one that’s slow.
According to a Google study, 53% of mobile users leave a site that takes longer than 3 seconds to load. The average mobile site takes about 15 seconds to load. That’s how much performance matters!
Every second your app takes longer to load, you’re probably losing customer conversions. Thankfully, for Laravel apps, it’s not a very difficult problem to solve.
1. Use In-Built Performance Quick Wins
Laravel offers a few in-built performance quick wins that can apply to any app.
The most significant performance quick win is route caching. Did you know that every time you boot your Laravel app, your app determines the middleware, resolves aliases, resolves route groups, and identifies the controller action and parameter inputs for every single route entry?
You can bypass the route processing by caching all the required routing information using the route:cache Artisan command:
“`bash
php artisan route:cache
This command can give you up to a 5x performance boost! It can make a significant impact on your app performance.
Besides route caching, Laravel also offers the following:
- [Configuration caching](https://laravel.com/docs/8.x/configuration#configuration-caching) to bypass parsing your `.env` and `config` files on every app boot.
- [View caching](https://laravel.com/docs/8.x/views#optimizing-views) to pre-compile your Blade template views.
- [Event caching](https://laravel.com/docs/8.x/events#event-discovery-in-production) to cache a manifest of all of your app's events and listeners.
Tip: You should make sure to add the above caching commands to your deployment script so that every time you deploy, your routes, config, views, and events are re-cached. Otherwise, any changes you make to your route or config files will not update in your application.
## 2. Optimize Composer
A common mistake sometimes made by Laravel developers is to install all dependencies in production. Some development packages such as Ignition record your queries, logs, and dumps in memory to give you a friendly error message with context for ease of debugging. While this is useful in development, it can slow down your application in production.
In your deployment script, make sure to use the `--no-dev` flag while installing packages using Composer:
"`bash
composer install --prefer-dist --no-dev -o
Additionally, make sure to use the `-o’ flag in production as above. This enables Composer to optimize the autoloader by generating a “classmap”.
You may choose to use the --classmap-authoritative flag instead of the `-o’ flag for further optimization if your app does not generate classes at runtime. Make sure to check out the Composer documentation on autoloader optimization strategies.
3. Choose The Right Drivers
Choosing the right cache, queue, and session drivers can make quite a difference to application performance.
For caching in production, we recommend the in-memory cache drivers such as Redis, Memcached, or DynamoDB. You may consider local filesystem caching for a single-server setup, although it would be slower than the in-memory options.
For queueing, we recommend the Redis, SQS, or Beanstalkd drivers. The database driver is not suitable for production environments and is known to have deadlock issues.
For sessions, we recommend the Database, Redis, Memcached, or DynamoDB drivers. The cookie driver has the file size and security limitations and is not recommended for production.
4. Queue Your Time-Consuming Tasks
There may be specific tasks that take a long time to perform during a typical web request. Laravel has a best-in-class queueing system that allows us to move time-consuming tasks to queued jobs so that your application can respond to requests with blazing speed.
Common examples of such tasks are parsing and storing a CSV file, interacting with third-party APIs, sending notifications to users, expensive database queries, and updating your search index.
5. Set Compression Headers On Text Format Files
Compression headers can have a significant impact on application performance. Ensure that you enable compression headers on your web server or CDN for text format files, like CSS, JS, XML, or JSON.
Most image formats are already compressed and are not text format files (with the exception of SVG, which is an XML document). So, image formats do not need to be compressed.
You may set up gzip or brotli (preferably both as brotli may not be supported for older browsers) at your web server or CDN level to achieve a huge performance boost.
Typically, compression would be able to reduce your file size by around 80%!
6. Set Cache Headers On Static Assets
Caching can provide a performance boost for your application, especially for static assets such as images, CSS, and JS files. It is recommended to enable cache-control headers at the webserver level or at your CDN level (if applicable). If you wish to set these headers at your Laravel app instead of the webserver, you may use Laravel’s cache control middleware.
Cache headers ensure that browsers don’t request static assets on subsequent visits to your website. This can enhance your user experience as your website loads faster on subsequent visits.
Make sure you use cache-busting so that when you change your CSS or JS code, browsers avoid relying on stale cached content. Laravel Mix provides cache busting out of the box.
7. Consider Using A CDN To Serve Assets
Content Delivery Networks (CDNs) are a geographically distributed group of servers that serve content closer to application visitors by using a nearby server. This enables visitors to experience faster loading times.
Besides faster loading times, CDNs also have other benefits such as decreased web server load, DDoS protection, and analytics on assets served.
Some popular CDNs include Cloudflare, AWS Cloudfront, and Azure CDN. Most CDNs are free for a certain usage threshold. Do consider using CDNs for boosting asset serving performance.
Laravel offers CDN support out of the box for Mix and the asset helper function.
8. Minify Your JS and CSS Code
Minification strips extra code from your application that is not essential for execution (like comments, whitespace, renaming variables with shorter names, and other optimizations). It’s always a good idea to minify JS and CSS files in production.
Laravel Mix provides minification out of the box when you run your production script.
9. Use Cache Wisely
Laravel has caching support built-in. Caching is best used for read-heavy workloads. These workloads typically involve either time-consuming data retrieval or data processing tasks.
Some common use cases of caching could include:
Caching static pages: Caching static pages is a no-brainer. Laravel’s website uses page caching for every single documentation page.
Fragment or partial caching: Sometimes, instead of caching full pages, it may be useful to cache page fragments. For instance, you may want to cache the page header that contains the name of the user and a profile pic. Instead of fetching the data from the database every time, you can cache the header fragment in one go.
Query caching: If your application queries the database on a high frequency for items that seldom change, it may be useful to cache the queries. For instance, if you run an e-commerce store, you might want to cache the items displayed on the store homepage rather than fetching them from the database on every store visit.
Remember that caching is not useful for the “long tail” (items rarely requested). Instead, it should be used carefully for any data retrieval that happens on a high frequency (as compared to data updates).
You must also make sure to invalidate or refresh your cache every time your cached content changes. For instance, if you are caching the profile header, refresh the cache once a user updates their profile pic.
10. Identify Your App’s Performance Bottlenecks
If some of your pages have high loading times or high memory usage, it may be essential to identify performance bottlenecks. Many tools exist within the Laravel ecosystem to help you do that, including Laravel Telescope, Laravel Debugbar, and Clockwork.
Some common performance bottlenecks include:
N+1 Queries: If your code executes one query for each record, it will result in more network round trips and a larger number of queries. This can be solved in Laravel using eager loading.
Duplicate Queries: If your code executes the same query more than once for the same request, it may slow down your application. Typically these issues can be solved by extracting data computation or retrieval to a separate class if multiple services or classes need the same set of data.
High Memory Usage: To reduce memory usage in your application, consider using lazy collections and query chunking for reducing model hydrations. For storing files, check out automatic streaming to reduce memory usage.
Slow Queries: If you have queries that are taking too long to execute, you should consider query caching and/or using explain statements to optimize query execution plans.
If you are unable to identify performance bottlenecks in your application using the debugging tools mentioned above, you may consider using profiling tools such as XDebug or Blackfire.
Conclusion
Performance is a wide topic, but Laravel has several components built-in such as Mix, queues, and caching that make performance look easy! We hope that you learned something new about boosting your app’s performance.
We can construct a new instance of this class by calling it:
>>> p = Point()
>>> p
<point.Point object at 0x7fd239fecfd0>
We have a Point object at this point, but this Point object really has no point because it has no functionality (it doesn’t store any useful data or have any methods).
We could manually add attributes to Point objects to store some data on them:
>>> p.x = 1
>>> p.y = 2
>>> p.x
1
But doing so would be a little silly.
It would be better if we could somehow call this class with arguments to store attributes automatically.
The initializer method
Currently, if we try to call this class with arguments, we’ll see an error:
>>> p = Point(1, 2)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: Point() takes no arguments
>>>
In order to accept arguments, we need to define a __init__ method in our class.
def __init__(self, x, y):
self.x = x
self.y = y
The first argument in our __init__ method will always be self (just like pretty much every other method).
After that we need to declare any arguments we want our class to accept.
The main thing you’ll pretty much always see in a __init__ method, is assigning to attributes.
This is our new Point class
class Point:
"""2-dimensional point."""
def __init__(self, x, y):
self.x = x
self.y = y
If we call it like before without any arguments, we’ll see an error because this class now requires two arguments, x and y:
>>> p = Point()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: __init__() missing 2 required positional arguments: 'x' and 'y'
We need to give our Point class two arguments in order to get a new instance of this class:
>>> p = Point(1, 2)
This Point object now has an x attribute and a y attribute:
>>> p.x
1
>>> p.y
2
That means our __init__ method was called!
Python calls __init__ whenever a class is called
Whenever you call a class, Python will construct a new instance of that class, and then call that class’ __init__ method, passing in the newly constructed instance as the first argument (self).
Unlike many programming languages, __init__ isn’t called the "constructor method".
Python’s __init__ method is called the initializer method.
The initializer method initializes our new class instance.
So by the point, that the initializer method is called the class instance has already been constructed.
Summary
When you make a new class in Python the first method you’ll likely make is the __init__ method.
The __init__ method allows you to accept arguments to your class.
More importantly, the __init__ method allows you to assign initial values to various attributes on your class instances.