Content Source:
Laravel Forge CLI
Laravel Forge launched their first official command-line tool that gives you a nice set of commands to manage your Forge servers, sites, and more.
The first release (v1.0) of the Forge CLI contains around thirty commands, including initiating deployments, viewing application logs, configuring SSH key authentication, and more.
Installation
You may install the Forge CLI as a global Composer dependency:
composer global require laravel/forge-cli
After it’s installed you can forge from your terminal and see usage:
Get Started
To view a list of all available Forge CLI commands and view the current version of your installation, you may run the forge
command from the command-line:
forge
Authenticating
You will need to generate an API token to interact with the Forge CLI. Tokens are used to authenticate your account without providing personal details. API tokens can be created from Forge’s API dashboard (opens new window).
After you have generated an API token, you should authenticate with your Forge account using the login command:
forge login
Current Server & Switching Servers
When managing Forge servers, sites, and resources via the CLI, you will need to be aware of your currently active server. You may view your current server using the server:current
command. Typically, most of the commands you execute using the Forge CLI will be executed against the active server.
forge server:current
Of course, you may switch your active server at any time. To change your active server, use the server:switch
command:
forge server:switch forge server:switch staging
To view a list of all available servers, you may use the server:list
command:
forge server:list
SSH Key Authentication
Before performing any tasks using the Forge CLI, you should ensure that you have added an SSH key for the forge
user to your servers so that you can securely connect to them. You may have already done this via the Forge UI. You may test that SSH is configured correctly by running the ssh:test
command:
forge ssh:test
To configure SSH key authentication, you may use the ssh:configure
command. The ssh:configure
command accepts a --key
option which instructs the CLI which public key to add to the server. In addition, you may provide a --name
option to specify the name that should be assigned to the key:
forge ssh:configure forge ssh:configure --key=/path/to/public/key.pub --name=sallys-macbook
After you have configured SSH key authentication, you may use the ssh
command to create a secure connection to your server:
forge ssh forge ssh server-name
Sites
To view the list of all available sites, you may use the site:list
command:
forge site:list
Initiating Deployments
One of the primary features of Laravel Forge is deployments. Deployments may be initiated via the Forge CLI using the deploy
command:
forge deploy forge deploy example.com
Updating Environment Variables
You may update a site’s environment variables using the env:pull
and env:push
commands. The env:pull
command may be used to pull down an environment file for a given site:
forge env:pull forge env:pull pestphp.com forge env:pull pestphp.com .env
Once this command has been executed the site’s environment file will be placed in your current directory. To update the site’s environment variables, simply open and edit this file. When you are done editing the variables, use the env:push
command to push the variables back to your site:
forge env:push forge env:push pestphp.com forge env:push pestphp.com .env
If your site is utilizing Laravel’s “configuration caching” feature or has queue workers, the new variables will not be utilized until the site is deployed again.
Viewing Application Logs
You may also view a site’s logs directly from the command-line. To do so, use the site:logs
command:
forge site:logs forge site:logs --follow # View logs in realtime forge site:logs example.com forge site:logs example.com --follow # View logs in realtime
Reviewing Deployment Output / Logs
When a deployment fails, you may review the output / logs via the Forge UI’s deployment history screen. You may also review the output at any time on the command-line using the deploy:logs
command. If the deploy:logs
command is called with no additional arguments, the logs for the latest deployment will be displayed. Or, you may pass the deployment ID to the deploy:logs
command to display the logs for a particular deployment:
forge deploy:logs forge deploy:logs 12345
Running Commands
Sometimes you may wish to run an arbitrary shell command against a site. The command
command will prompt you for the command you would like to run. The command will be run relative to the site’s root directory.
forge command forge command example.com forge command example.com --command="php artisan inspire"
Tinker
As you may know, all Laravel applications include “Tinker” by default. To enter a Tinker environment on a remote server using the Forge CLI, run the tinker
command:
forge tinker forge tinker example.com
Resources
Forge provisions servers with a variety of resources and additional software, such as Nginx, MySQL, etc. You may use the Forge CLI to perform common actions on those resources.
Checking Resource Status
To check the current status of a resource, you may use the {resource}:status
command:
forge daemon:status forge database:status forge nginx:status forge php:status # View PHP logs (default PHP version) forge php:status 8.0 # View PHP 8.0 logs
Viewing Resources Logs
You may also view logs directly from the command-line. To do so, use the {resource}:logs
command:
forge daemon:logs forge daemon:logs --follow # View logs in realtime forge database:logs forge nginx:logs # View error logs forge nginx:logs access # View access logs forge php:logs # View PHP logs (default PHP version) forge php:logs 8.0 # View PHP 8.0 logs
Restarting Resources
Resources may be restarted using the {resource}:restart
command:
forge daemon:restart forge database:restart forge nginx:restart forge php:restart # Restarts PHP (default PHP version) forge php:restart 8.0 # Restarts PHP 8.0
Connecting To Resources Locally
You may use the {resource}:shell
command to quickly access a command line shell that lets you interact with a given resource:
forge database:shell forge database:shell my-database-name forge database:shell my-database-name --user=my-user
For more information and to develop web applications using Laravel, Hire Laravel Developer from us as we give you a high-quality product by utilizing all the latest tools and advanced technology. E-mail us any clock at – hello@hkinfosoft.com or Skype us: “hkinfosoft”.
To develop custom web apps using Laravel, please visit our technology page.
Content Source:
- laravel-news.com
- forge.laravel.com
Find N+1 problems instantly by disabling lazy loading
In the next release of Laravel 8, you can strictly disable lazy loading entirely, resulting in an exception:
Preventing lazy loading in development can help you catch N+1 bugs earlier on in the development process. The Laravel ecosystem has various tools to identify N+1 queries. However, this approach brings the issue front-and-center by throwing an exception.
Demo
Let’s walk through this feature real quick by spinning up a development version of the framework 8.x branch since this feature is not out yet at the time of writing. Once released, you will have this feature without switching to the latest 8.x branch.
Setup
First, create a new application:
laravel new strict-lazy-demo
Next, we’ll update the laravel/framework version in composer.json to make sure we have this feature (if you’re trying it out before the next release) by adjusting the version to 8.x-dev:
{ "require": { "laravel/framework": "8.x-dev" } }
Next, run composer update to make sure you get the latest version of the code for this branch:
composer update laravel/framework
At this point, you should set up your preferred database. We like running a local MySQL instance using Laravel’s defaults of using the root user without a password. We find it convenient to use the default .env values locally to get started quickly without any configuration.
mysql -uroot -e"create database strict_lazy_demo"
Once you configure your database of choice, make sure you can migrate:
php artisan migrate:fresh
Demo Data
We’ll create a Post model and define a one-to-many relationship from the User model to demonstrate this feature. We’ll start by creating the Post model and accompanying files:
# Create a model with migration and factory php artisan make:model -mf Post
First, let’s define our Post migration and factory configuration:
// Your filename will differ based on when you create the file. // 2021_05_21_000013_create_posts_table.php Schema::create('posts', function (Blueprint $table) { $table->id(); $table->foreignIdFor(\App\Models\User::class); $table->string('title'); $table->longText('body'); $table->timestamps(); });
Next, define your PostFactory definition method based on the above schema:
/** * Define the model's default state. * * @return array */ public function definition() { return [ 'user_id' => \App\Models\User::factory(), 'title' => $this->faker->sentence(), 'body' => implode("\n\n", $this->faker->paragraphs(rand(2,5))), ]; }
Finally, open up the DatabaseSeeder file and add the following in the run() method:
/** * Seed the application's database. * * @return void */ public function run() { \App\Models\User::factory() ->has(\App\Models\Post::factory()->count(3)) ->create() ; }
Associating Models and Prevent Lazy Loading
Now that we have the migration, seeder, and model created, we are ready to associate a User with the Post model to demo this feature.
Add the following method to the User model to give the user an association with Posts:
// app/Models/User.php /** * @return \Illuminate\Database\Eloquent\Relations\HasMany */ public function posts() { return $this->hasMany(Post::class); }
With that in place, we can migrate and seed the database:
php artisan migrate:fresh --seed
If all went well, we should see something like the following in the console:
We can now using tinker to inspect our seeded data and relationship:
php artisan tinker >>> $user = User::first() => App\Models\User {#4091 id: 1, name: "Nedra Hayes", email: "bruen.marc@example.com", email_verified_at: "2021-05-21 00:35:59", created_at: "2021-05-21 00:35:59", updated_at: "2021-05-21 00:35:59", } >>> $user->posts => Illuminate\Database\Eloquent\Collection {#3686 all: [ App\Models\Post {#3369 id: 1, ...
The $user->posts
property actually calls the database, thus is “lazy” but is not optimized. The convenience of lazy-loading is nice, but it can come with heavy performance burdens in the long-term.
Disabling Lazy Loading
Now that we have the models set up, we can disable lazy loading across our application. You’d likely want to only disable in non-production environments, which is easy to achieve! Open up the AppServiceProvider class and add the following to the boot() method:
// app/Providers/AppServiceProvider.php public function boot() { Model::preventLazyLoading(! app()->isProduction()); }
If you run a php artisan tinker session again, this time you should get an exception for a lazy loading violation:
php artisan tinker >>> $user = \App\Models\User::first() => App\Models\User {#3685 id: 1, name: "Nedra Hayes", email: "bruen.marc@example.com", email_verified_at: "2021-05-21 00:35:59", #password: "$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi", #remember_token: "jHSxFGKOdw", created_at: "2021-05-21 00:35:59", updated_at: "2021-05-21 00:35:59", } >>> $user->posts Illuminate\Database\LazyLoadingViolationException with message 'Attempted to lazy load [posts] on model [App\Models\User] but lazy loading is disabled.'
If you want to visualize what happens if you use lazy loading in a view file, modify the default route as follows:
Route::get('/', function () { return view('welcome', [ 'user' => \App\Models\User::first() ]); });
Next, add the following somewhere in the welcome.blade.php file:
<h2>Posts</h2> @foreach($user->posts as $post) <h3>{{ $post->title }}</h3> <p> {{ $post->body }} </p> @endforeach
If you load up your application through Valet or artisan serve, you should see something like the following error page:
Though you’ll get exceptions during development, accidentally deploying code that triggers lazy-loading will continue to work as long as you set environment checking correctly in the service provider.
For more information and to develop web applications using Laravel, Hire Laravel Developer from us as we give you a high-quality product by utilizing all the latest tools and advanced technology. E-mail us any clock at – hello@hkinfosoft.com or Skype us: “hkinfosoft”.
To develop custom web apps using Laravel, please visit our technology page.
Content Source:
- laravel-news.com
What is Application Performance Monitoring (APM)?
Application Performance Monitoring (APM), as the name suggests, is the process of monitoring the performance of the many aspects of your application.
When an end-user logs into your application, for even just one web page to load on their device, there are very many backstage components that need to come together and operate in synchrony to ensure a smooth and fast experience. These include network components (that carry the bytes of data), software components (e.g., server-side frameworks, front-end code, and other dependencies), and hardware components (i.e., CPU processors, memory, and storage of machines that host your web servers, APIs, databases, file systems, etc.) It can become overwhelming to manually keep track of your application performance on all these different levels and across all components. This is even truer when you ideally want monitoring and checks to happen all the time, in real-time!
Well, this is precisely the problem that APM solutions target. APM tools, like ScoutAPM, allow organizations to get a detailed analysis of the performance of your applications, in real-time. This includes critical information about server requests, response times, time-consuming methods and end-points, errors and their root cause analysis, and lots more – presented in a way that is easy to understand and troubleshoot.
These performance insights provide a lot of valuable information about optimizing resource allocations and effective cost reductions while surfacing other issues that could potentially fail your application – and all before the user gets a hint of anything being amiss.
Apart from presenting a bird’s eye view of what is happening within your application as a whole, APM tools provide you with your application’s score on particular metrics that quantify its performance along different grounds.
They provide metrics like request rates, response times, server load, CPU and memory usage, application throughput, server health status, and lots more, enabling organizations to understand what drives their application’s performance or failures.
They bring to light and help you identify performance bottlenecks, memory leaks, bloat, slow database queries, wasted execution cycles, and much more in your application. Additionally, tools like ScoutAPM enable teams to trace the cause of these issues to the specific line of the code causing them so that developers need to spend less time debugging and more time building.
Different platforms, frameworks, and APIs allow you to monitor the performance of a few of your applications’ components – for example, your cloud service provider could provide information about resource usage, logging frameworks could help you capture backend errors and processing times, etc. But wouldn’t it be much more useful to have everything you need under one roof – as a one-stop platform to provide all the information about everything you might need to know about your application’s performance.
Different organizations might want to optimize their application’s performance on different metrics. Some teams might want to prioritize more reliability and uptime, over other applications that might want to focus on higher speeds and lower response times. In this regard, equally important is the amount of flexibility that many of these tools offer in creating customizable dashboards – allowing you to focus on aspects of performance that matter the most to your application.
APM tools, therefore, can go a long way in resolving issues faster, preventing interruptions, boosting performance, increasing business and revenue, and understanding customer interactions.
Let us look at some common use cases of APM solutions to get a pragmatic understanding of how helpful they can be for developers and organizations to ensure that everything about their application is on track.
Common Use Cases for APMs
Use case #1 – Application Development
Application development involves a lot of code tweaking, solving bugs, adding features, experimenting with different libraries and frameworks, refactoring, and so on. This can lead to minor fluctuations in performance that developers might want to track and monitor throughout the development lifecycle and in the staging and production environments.
Therefore, application development can benefit a great deal from the insights provided by APM tools. These could be insights about the application’s performance or an in-depth analysis of issues down to the code level. By highlighting the source of the problem and isolating issues to specific lines (or methods) in the code causing them, these tools narrow down the areas of the project that they should be focusing more on.
Below is an example of code traceability in ScoutAPM, with Github integration enabled.
Use case #2 – Identifying Performance Bottlenecks
A bottleneck in software engineering refers to the negative effect on performance caused by the limited ability or capacity of one component of the system – similar to impeding water flow caused near a bottle’s constricted neck. A bottleneck is like the slower car on a single-track road that keeps everyone else waiting.
Even with the best software and hardware infrastructure in place, all it takes is one sub-optimal component to make your application crawl when it could be flying. APM tools help you identify performance bottlenecks with accuracy. These range from bottlenecks in disk usage, CPU utilization, memory to software and network components. APM platforms like Scout provide a complete analysis of several metrics like the memory allocation, response times, throughput, and error rates corresponding to each end-point in your application. Metrics like these provide insights into the long-term performance of these applications and help highlight where such bottlenecks lie.
It is important to note that if you are just starting out with web development, and working on smaller, personal projects, understanding the importance of APM tools might not come easily or seem super relevant. However, these tools become exponentially more valuable as your application(s) scale-up and cater to hundreds or thousands of users.
For more information and to develop web applications using Laravel, Hire Laravel Developer from us as we give you a high-quality product by utilizing all the latest tools and advanced technology. E-mail us any clock at – hello@hkinfosoft.com or Skype us: “hkinfosoft”.
To develop custom web apps using Laravel, please visit our technology page.
Content Source:
- laravel-news.com
Laravel component Media Library
Media Library can associate files with Eloquent models. You can, for instance, associate images with a blog post model. In your Blade view, you can retrieve URLs to the associated images. It can handle multiple collections, work with multiple filesytems, create zips on the fly to download multiple files, use a customized directory structure, save bandwidth using responsive images and much more.
The problem with traditional uploads
Before exploring Media Library Pro, let’s first explained why we built it in the first place. Here’s how a traditional upload form might look like. It uses a regular input of type file.
<form method="POST" enctype="multipart/form-data"> <x-grid> @csrf <x-field label="name"> <x-input id="name" name="name" placeholder="Your first name" /> </x-field> <x-field label="file"> <input type="file" name="file"> @error('file') {{ $message }} @enderror </x-field> <x-button dusk="submit">Submit</x-button> </x-grid> </form>
There are two big problems with this standard upload element.
First, the upload process only starts when the form is submitted. For small files in small forms, this might not be a problem. But imagine you’re uploading a multi MB file in a form. When submitting the form, you now have to wait for the upload to complete before seeing the submission results.
The second problem is something that has bothered us for a long, long time. Imagine that the input field is part of a form of which some fields are required. You’re selecting a file, submitting the form, leaving some of the required fields empty. You get redirected back to the form where error messages are now displayed. Your previous file selection is gone, and you need to select the file again.
Media Library Pro
Media Library Pro is a paid add-on package that offers Blade, Vue, and React components to upload files to your application. It ships with two components. The first one is the attachment component. It is meant to be used on a public-facing page where you want users to upload one or multiple files.
The second one is called the collection component. This one can manage the files in an existing collection. It is meant to be used in the admin part of your app.
Both of these components are available as Vue, React and Blade components. Under the hood, the Blade components are powered by Caleb’s excellent Livewire package.
These components are straightforward to install and are documented in great detail.
Let’s take a look at both the `Attachment` and `Collection` component. In the remainder of the blog post, we’ll use the Blade version of the examples, but rest assured that everything shown can also be done with the Vue and React counterparts.
The Attachment component
To get started with the Attachment Blade component you’ll have to use x-media-library-attachment in your view.
<form method="POST"> @csrf <input id="name" name="name"> <x-media-library-attachment name="avatar"/> <button type="submit">Submit</button> </form>
Here’s how it looks like after we’ve selected a file but before submitting the form.
The x-media-library-attachment has taken care of the upload. The file is now stored as a temporary upload. In case there are validation errors when submitting the form, the x-media-library-attachment will display the temporary upload when you get redirected back to the form. There’s no need for the user to upload the file again.
Here’s the form request used to validate the uploaded.
namespace App\Http\Requests\Blade; use Illuminate\Foundation\Http\FormRequest; use Spatie\MediaLibraryPro\Rules\Concerns\ValidatesMedia; class StoreBladeAttachmentRequest extends FormRequest { use ValidatesMedia; public function rules() { return [ 'name' => 'required', 'media' => ['required', $this->validateSingleMedia() ->maxItemSizeInKb(3000), ], ]; } }
By applying the ValidatesMedia trait, you get access to the validateSingleMedia, which allows you to validate the upload. You can chain on many validation methods, which are documented here.
In your controller, you can associate the upload file to any model you’d like.
$formSubmission ->addFromMediaLibraryRequest($request->media) ->toMediaCollection('images');
And that is all you need to do!
The attachment component can be used to handle multiple uploads as well. In this video, you’ll see how that is done.
The Collection component
You can manage the entire contents of a media library collection with x-media-library-collection component. This
component is intended to use in admin sections.
Here is an example where we will administer an images collection of a $formSubmission model.
<form method="POST"> @csrf <x-field label="name"> <x-input id="name" name="name" autocomplete="off" placeholder="Your name" value="{{ old('name', $formSubmission->name) }}"/> </x-field> <x-field label="Images"> <x-media-library-collection name="images" :model="$formSubmission" collection="images" max-items="3" rules="mimes:png,jpeg" /> </x-field> <x-button dusk="submit" type="submit">Submit</x-button> </form>
Here’s how that component looks like:
This component will display the contents of the entire collection. Files can be added, removed, updated, and reordered.
To validate the response of the form, a form request like this one can be used:
namespace App\Http\Requests\Blade; use Illuminate\Foundation\Http\FormRequest; use Spatie\MediaLibraryPro\Rules\Concerns\ValidatesMedia; class StoreBladeCollectionRequest extends FormRequest { use ValidatesMedia; public function rules() { return [ 'name' => 'required', 'images' => [$this->validateMultipleMedia() ->maxItems(3) ->itemName('required'), ], ]; } }
Again, you need to ValidatesMedia trait. This time the validateMultipleMedia should be used. You can chain on the other validation methods, which are documented here.
In the controller, you can associate the media in the collection component with your model using the syncFromMediaLibraryRequest method.
Here’s the relevant code in the controller of the demo app.
$formSubmission ->syncFromMediaLibraryRequest($request->images) ->toMediaCollection('images');
Adding custom properties
When using the collection component, you probably want to add some extra fields to be displayed. We’ve made this a straightforward thing to do.
In the screenshot below, we added the Extra field field.
You can achieve this by passing a blade view to the fields-view prop of the x-media-library-collection.
<x-media-library-collection name="images" :model="$formSubmission" collection="images" max-items="3" rules="mimes:png,jpeg" fields-view="uploads.blade.partials.custom-properties" />
In that custom-properties view, you can put anything that should be displayed in the right half of the collection component.
Here’s the content of that custom-propertiesview.
@include('media-library::livewire.partials.collection.fields') <div class="media-library-field"> <label class="media-library-label">Extra field</label> <input dusk="media-library-extra-field" class="media-library-input" type="text" {{ $mediaItem->customPropertyAttributes('extra_field') }} /> @error($mediaItem->customPropertyErrorName('extra_field')) <span class="media-library-text-error"> {{ $message }} </span> @enderror </div>
In the form request, you can use the customProperty to validate any extra custom attributes. The second argument of the function can take any validator in Laravel.
namespace App\Http\Requests\Blade; use Illuminate\Foundation\Http\FormRequest; use Spatie\MediaLibraryPro\Rules\Concerns\ValidatesMedia; class StoreBladeCollectionCustomPropertyRequest extends FormRequest { use ValidatesMedia; public function rules() { return [ 'name' => 'required', 'images' => [$this->validateMultipleMedia() ->maxItems(3) ->itemName('required|max:30') ->customProperty('extra_field', 'required|max:30'), ], ]; } }
In the controller where you process the form submission, you should use the withCustomProperties method to whitelist any extra attributes that you want to sync with your media.
$formSubmission ->syncFromMediaLibraryRequest($request->images) ->withCustomProperties('extra_field') ->toMediaCollection('images');
Customizing the look and feel
By default, both the Attachment and Collection components already look good. Probably you’d like to adapt them so they match the look of your app.
Luckily, this is easy to do. The styles that ship with Media Library Pro can be used by importing or linking dist/styles.css. The styles were built with a default tailwind.config.js.
You can customize the styles by importing src/styles.css and run every @apply rule through your own tailwind.config.js
/* app.css */ @tailwind base; @tailwind components; @tailwind utilities; @import "src/styles.css"; …
How temporary files are used
To achieve that behavior where uploaded files are preserved when a form validation error occurs, we use temporary uploads.
Testing the components
Inside the private spatie/laravel-medialibrary-pro repo, there are a lot of tests to make sure the back end integration and the Vue, React, and Blade front end components are working as expected.
We also wanted to have browser tests that ensure that front end components work perfectly with the back end and vice versa. That’s why we added Dusk tests in our demo application. You can see them here.
Let’s take a look at one of them:
/** * @test * * @dataProvider routeNames */ public function it_can_handle_a_single_upload(string $routeName) { $this->browse(function (Browser $browser) use ($routeName) { $browser ->visit(route($routeName)) ->type('name', 'My name') ->attach('@main-uploader', $this->getStubPath('space.png')) ->waitForText('Remove') ->waitUntilMissing('.media-library-progress-wrap.media-library-progress-wrap-loading') ->press('@submit') ->assertSee('Your form has been submitted'); $this->assertCount(1, FormSubmission::get()); $this->assertEquals('space.png', FormSubmission::first()->getFirstMedia('images')->file_name); }); }
This test will upload a file and make sure that the file is associated with a model after the form is submitted.
A thing to note here is that @dataProvider attribute. This will make PHPUnit run the test for each result returned by the routeNames function defined in the same file.
public function routeNames(): array { return [ ['vue.attachment'], ['react.attachment'], ['blade.attachment'], ]; }
You can see that in combination with the routeNames function, the it_can_handle_a_single_upload will run for the vue.attachment, react.attachment and blade.attachment routes. Visiting these routes will display the form that will use the Vue, React, or Blade component, respectively. So, this one test covers a lot of logic. It makes sure that the component work using any technology. This gives us a lot of confidence that all of the components are working correctly.
For more information and to develop web application using Laravel, Hire Laravel Developer from us as we give you a high-quality product by utilizing all the latest tools and advanced technology. E-mail us any clock at – hello@hkinfosoft.com or Skype us: “hkinfosoft”. To develop custom web apps using React JS, please visit our technology page.
Content Source:
- laravel-news.com
Laravel 8 is just released!
Laravel 8 is now released and includes many new features including Laravel Jetstream, a models directory, model factory classes, migration squashing, rate-limiting improvements, time testing helpers, dynamic blade components, and many more features.
Before we jump into the new features, we’d like to point out that starting with version 6, Laravel now follows semver and will release a new major version every six months. You can see how the release process works here.
Laravel Jetstream
Laravel Jetstream improves upon the existing Laravel UI scaffolding found in previous versions. It provides a starting point for new projects, including login, registration, email verification, two-factor authentication, session management, API support via Laravel, and team management.
Models Directory
Laravel 8’s application skeleton includes an app/Models directory. All generator commands assume models exist in app/Models; however if this directory doesn’t exist, the framework will assume the application keeps models within the app/ folder.
Model Factory Classes
Eloquent model factories are now class-based starting in Laravel 8, with improved support for relationships between factories (i.e., a user has many posts). I think you’ll agree how awesome the new syntax is for generating records via the new and improved model factories:
use App\Models\User; User::factory()->count(50)->create(); // using a model state "suspended" defined within the factory class User::factory()->count(5)->suspended()->create();
Migration Squashing
If your application contains many migration files, you can now squash them into a single SQL file. This file will be executed first when running migrations, followed by any remaining migration files that are not part of the squashed schema file. Squashing existing migrations can decrease migration file bloat and possibly improve performance while running tests.
Improved Rate Limiting
Laravel 8 brings improvements to existing rate limiting functionality while supporting backward compatibility with the existing throttle middleware and offering far more flexibility. Laravel 8 has the concept of Rate Limiters that you can define via a facade:
use Illuminate\Cache\RateLimiting\Limit; use Illuminate\Support\Facades\RateLimiter; RateLimiter::for('global', function (Request $request) { return Limit::perMinute(1000); });
As you can see, the for() method takes the HTTP request instance, giving you full control over limiting requests dynamically.
Time Testing Helpers
Laravel users have enjoyed full control over time modification via the excellent Carbon PHP library. Laravel 8 brings this one step further by providing convenient test helpers for manipulating the time within tests:
// Travel into the future... $this->travel(5)->milliseconds(); $this->travel(5)->seconds(); $this->travel(5)->minutes(); $this->travel(5)->hours(); $this->travel(5)->days(); $this->travel(5)->weeks(); $this->travel(5)->years(); // Travel into the past... $this->travel(-5)->hours(); // Travel to an exact time... $this->travelTo(now()->subHours(6)); // Return back to the present time... $this->travelBack();
When using these methods, the time will reset between each test.
Dynamic Blade Components
Sometimes you need to render a blade component dynamically at runtime. Laravel 8 provides the ‘<x-dynamic-component/>’ to render the component:
<x-dynamic-component :component="$componentName" class="mt-4" />
Job Batching
Laravel’s job batching feature allows you to easily execute a batch of jobs and then perform some action when the batch of jobs has completed executing.
The new batch method of the Bus facade may be used to dispatch a batch of jobs. Of course, batching is primarily useful when combined with completion callbacks. So, you may use the then, catch, and finally methods to define completion callbacks for the batch. Each of these callbacks will receive an Illuminate\Bus\Batch instance when they are invoked:
use App\Jobs\ProcessPodcast; use App\Podcast; use Illuminate\Bus\Batch; use Illuminate\Support\Facades\Bus; use Throwable; $batch = Bus::batch([ new ProcessPodcast(Podcast::find(1)), new ProcessPodcast(Podcast::find(2)), new ProcessPodcast(Podcast::find(3)), new ProcessPodcast(Podcast::find(4)), new ProcessPodcast(Podcast::find(5)), ])->then(function (Batch $batch) { // All jobs completed successfully... })->catch(function (Batch $batch, Throwable $e) { // First batch job failure detected... })->finally(function (Batch $batch) { // The batch has finished executing... })->dispatch(); return $batch->id;
Improved Maintenance Mode
In previous releases of Laravel, the php artisan down maintenance mode feature may be bypassed using an “allow list” of IP addresses that were allowed to access the application. This feature has been removed in favor of a simpler “secret” / token solution.
While in maintenance mode, you may use the secret option to specify a maintenance mode bypass token:
php artisan down --secret="1630542a-246b-4b66-afa1-dd72a4c43515"
After placing the application in maintenance mode, you may navigate to the application URL matching this token and Laravel will issue a maintenance mode bypass cookie to your browser:
https://example.com/1630542a-246b-4b66-afa1-dd72a4c43515
When accessing this hidden route, you will then be redirected to the / route of the application. Once the cookie has been issued to your browser, you will be able to browse the application normally as if it was not in maintenance mode.
Pre-Rendering The Maintenance Mode View
If you utilize the php artisan down command during deployment, your users may still occasionally encounter errors if they access the application while your Composer dependencies or other infrastructure components are updating. This occurs because a significant part of the Laravel framework must boot in order to determine your application is in maintenance mode and render the maintenance mode view using the templating engine.
For this reason, Laravel now allows you to pre-render a maintenance mode view that will be returned at the very beginning of the request cycle. This view is rendered before any of your application’s dependencies have loaded. You may pre-render a template of your choice using the down command’s render option:
php artisan down --render="errors::503"
For more information and to develop web application using Laravel, Hire Laravel Developer from us as we give you a high-quality product by utilizing all the latest tools and advanced technology. E-mail us any clock at – hello@hkinfosoft.com or Skype us: “hkinfosoft”. To develop custom web apps using React JS, please visit our technology page.
Content Source:
- laravel-news.com
- laravel.com
Lazy Loading React Components
Let’s take a look at how you can leverage this feature in your application in order to improve performance and build a better experience for users.
As always, when building with components it’s useful to organize them in a collection using tools like Bit. Then you can share and use your components in any app you’d like, to speed development and keep your code DRY.
What is React.lazy()
It is a new function in react that lets you load react components lazily through code splitting without help from any additional libraries. Lazy loading is the technique of rendering only-needed or critical user interface items first, then quietly unrolling the non-critical items later. It is now fully integrated into core react library itself. We formerly used react-loadable to achieve this but now we have react.lazy() in react core.
Suspense
Suspense is a component required by the lazy function basically used to wrap lazy components. Multiple lazy components can be wrapped with the suspense component. It takes a fallback property that accepts the react elements you want to render as the lazy component is being loaded.
Why is Lazy Loading (& Suspense) Important
Firstly, bundling involves aligning our code components in progression and putting them in one javascript chunk that it passes to the browser; but as our application grows, we notice that bundle gets very cumbersome in size. This can quickly make using your application very hard and especially slow. With Code splitting, the bundle can be split to smaller chunks where the most important chunk can be loaded first and then every other secondary one lazily loaded.
Also, while building applications we know that as a best practise consideration should be made for users using mobile internet data and others with really slow internet connections. We the developers should always be able to control the user experience even during a suspense period when resources are being loaded to the DOM.
Getting Started
According to the react official documentation, you have webpack bundling already configured for use out of the box if you use:
- CRA (create react app)
- Next js
- Gatsby
If you are not, you will need to setup bundling yourself. For example, see the Installation and Getting Started guides on the Webpack official documentation.
you can create one yourself and make the changes below, the src folder of your application should look like this:
1. Artists.js
import React from 'react'; import './App.css'; import artists from "./store"; export default function Artists(){ return ( <> <h1>MTV Base Headline Artists 2019</h1> {artists.map(artist =>( <div id="card-body" key={artist.id}> <div className="card"> <h2>{artist.name}</h2> <p>genre: {artist.genre}</p> <p>Albums released: {artist.albums}</p> </div> </div> ))} </> ); }
2. Store.js
export default [ { id: "1", name: "Davido", country: "Nigeria", genre: "Afro-Pop", albums: "2" }, { id: "2", name: "AKA", country: "South-Africa", genre: "Hip-Hop", albums: "4" }, { id: "3", name: "Seyi Shay", country: "Nigeria", genre: "R&B", albums: "2" }, { id: "4", name: "Sauti Sol", country: "Kenya", genre: "Soul", albums: "3" } ];
3. Index.js
import React from 'react'; import ReactDOM from 'react-dom'; import './index.css'; import Artists from './Artists'; class App extends React.Component { render(){ return( <div className="App"> <Artists /> </div> ); } } ReactDOM.render(<App />, document.getElementById('root'));
4. App.css
.App { text-align: center; } h1 { padding: 30px; } #card-body { display: inline-flex; padding: 10px; margin: 30px 30px; border: 5px solid rgb(93, 171, 207); border-radius: 8px; background: lightblue; }
Now let us see how to use react.lazy and suspense to handle lazy loading of the artists component.
- Head to the index.js file and import lazy and suspense from react like this:
import { Suspense, lazy } from 'react';
- To render a dynamic import as a regular component, the react documentation gives the react.lazy function syntax like so:
const OtherComponent = React.lazy(() => import('./OtherComponent')); function MyComponent() { return ( <div> <OtherComponent /> </div> ); }
- Trying it out with our Artists component we would have something like this:
const Artists = React.lazy(() => import('./Artists')); function MyComponent() { return ( <div> <Artists /> </div> ); }
If the module containing the Artists is not yet loaded by the time my App component renders, we must show some fallback content while we’re waiting for it to load. This can be a loading indicator, brought in action by the suspense component. Below is the syntax for adding suspense component to react.lazy:
const OtherComponent = React.lazy(() => import('./OtherComponent')); function MyComponent() { return ( <div> <Suspense fallback={<div>Loading...</div>}> <OtherComponent /> </Suspense> </div> ); }
With our artists component, this becomes:
const Artists = React.lazy(() => import('./Artists')); function MyComponent() { return ( <div> <Suspense fallback={<div>Loading...</div>}> <Artists /> </Suspense> </div> ); }
Putting it all together, your index.js file should be like this:
import React, { lazy, Suspense } from 'react'; import ReactDOM from 'react-dom'; import './index.css'; // import Artists from './Artists'; const Artists = lazy(() => import('./Artists')) class App extends React.Component { render(){ return( <div className=”App”> <Suspense fallback={<h1>Still Loading…</h1>}> <Artists /> </Suspense> </div> ); } } ReactDOM.render(<App />, document.getElementById('root'));
On your localhost it should be really fast and you might not be able to spot the changes. You can however create a timer helper or just simulate a slower network that would be able to show you exactly how the changes occur in milliseconds. This can be done by:
- opening the dev tools on your browser
- choosing the network tab
- clicking on the online tab at the far right to reveal other options (presets)
- choosing fast 3G
Now you can refresh your browser and watch how lazy loading occurs..
Multiple Lazy Components
Let us quickly add a small component that renders a header and see how the react.lazy function handles it with only one suspense component.
Create a performers.js file in your src folder and add the code below:
import React from 'react'; import './App.css'; export default function Performers(){ return ( <> <h2>These are the MTV Base Headline Artists...</h2> </> ); }
Then add the lazy component line in the index.js file and it should now look like this:
import React, { lazy, Suspense } from 'react'; import ReactDOM from 'react-dom'; import './index.css'; const Artists = lazy(() => import('./Artists')) const Performers = lazy(() => import('./Performers')) class App extends React.Component { render(){ return( <div className=”App”> <Suspense fallback={<h1>Still Loading…</h1>}> <Artists /> <Performers /> </Suspense> <strong> </div> ); } } ReactDOM.render(<App />, document.getElementById('root'));
This should now show the two lazily loaded components show up at once after the placeholder element from the suspense has been rendered.
This is quite unlike loadable which would have to render the loading element for each lazy component.
Note: React.lazy and Suspense is not yet available for server-side rendering. If you want to do code-splitting in a server-rendered app, Loadable Components is highly recommended. It has a nice guide for bundle splitting with server-side rendering.
For more Information and to build a website using React JS, Hire React Developer from us as we give you a high-quality product by utilizing all the latest tools and advanced technology. E-mail us any clock at – hello@hkinfosoft.com or Skype us: “hkinfosoft“.To develop your custom website using React JS, please visit our technology page.
Content Source:
- blog.bitsrc.io
10 React component libraries you should know in 2018
The popularity of React seems to be ever growing. React is leading in popularity in Stack overflow’s 2017 most loved component libraries.
React’s virtual DOM, the ability to declaratively describe a user interface and model the state of that interface, low barriers to entry for a decent JavaScript developer, all make React a great go-to library for building UI’s.
Another great reason for working with React is components. Components let you split the UI into independent, reusable pieces, and think about each piece in isolation. To help kickstart your work with React components, here are 10 great React component libraries you should consider for your next app.
Many of these libraries can also be combined with Bit, which enables you to isolate and manage components in any SCM repository, share them to a Scope to make components individually available to discover and install, and keep them synced between different repositories and projects.
1. React Material-UI
React Material-UI is a set of React components that implements Google’s Material Design. With over 30k stars on GitHub, it is probably the most popular React component library. The library’s v1 is coming up.
2. React-Bootstrap
React-Bootstrap is a reusbale React component library with the look-and-feel of Twitter’s popular Bootstrap. At over 11k stars, its simplicity receives wide popularity in the community.
3. React toolbox
React Toolbox is a set of React components that implements Google Material Design specification. It’s built on top of some the trendiest proposals like CSS Modules (written in SASS), Webpack and ES6. The library’s website provides a live component playground.
4. React Belle
React Belle is a set of React components optimized to work both on mobile & desktop devices. The styles are highly customizable so you can configure the base styles of all the components as well as modify each one of them individually. Here is also a nice example.
5. React Grommet
React Grommet provides a rich selection of components grouped by usage classifications, and all components are accessible, cross-browser compatible and support theme customization.
6. Material Components Web
Material Components Web is developed by a core team of engineers and UX designers at Google, and its components enable a reliable development workflow to build beautiful and functional web projects. It has replaced react-mdl (which is now deprecated), already reaching nearly 7k stars.
7. Ant Design React
Following the Ant Design specification, React Ant Design is a React UI library that contains a set of components and demos. It’s written in TypeScript with complete defined types, and provides an NPM+ webpack + dva front-end development workflow.
8. Semantic UI React
Semantic UI React is the official Semantic-UI-React integration. With nearly 5k stars and used by Netflix and Amazon, these components provide an interesting and flexible arsenal.
9. Onsen UI
Onsen UI React Components made available with Onsen UI React bindings and provide hybrid mobile apps with React and Onsen UI Framework. With 81 contributors and over 5.6k stars it’s an interesting library to consider.
10. React Virtualized
At nearly 8k stars, React Virtualized provides React components for efficiently rendering large lists and tabular data.
Individual components
Individual components can be found in the popular awesome-react and awesome-react-components projects. Different components can also be grouped into a Scope on the Bit community hub to install and sync components between different repos and projects.
For more information and to build your web app. Hire React.js Developer from us, as we give you high quality product by utilizing all the latest tools and advanced technology. E-mail us any clock at – hello@hkinfosoft.com or Skype us: “hkinfosoft“.
To develop custom web app using React.js, please visit our technology page.
Content Source:
- blog.bitsrc.io
11 Angular component libraries you should know in 2018
According to Stack Overflow’s 2017 survey, Angular remains the world’s most popular front-end framework.
Angular’s framework approach is to keep most of the magic under the hood, providing tooling and best practices on top. Angular encourages you to use components, splitting your UI into separated and reusable pieces.
To work with individual components from different libraries, you can also use Bit. It provides isolation and control for components within a project, and enables you to share and sync them between different project. Individual components shared with Bit can also be installed used the NPM / Yarn client.
1. Material2
Angular’s official component library implementing Google’s material design, built with Angular and TypeScript. These UI components serve as an example of how to write Angular code following the Angular team’s best practices. Individual components can also be installed from this Bit Scope.
2. NGX Bootstrap
At 3.5K stars, this library contains all core (and not only) Bootstrap components powered by Angular. With performance for both Mobile and Desktop, it’s designed with extensibility and adaptivity in mind.
3. Prime NG
A comprehensive component suit including over 70 UI components with different themes from material to flat design. At 3.3k stars and used by eBay, Fox and more organizations, this library is an interesting option to consider.
4. NG Bootstrap
At 4.5K stars, and replacing angular-ui bootstrap which is no longer maintained, this popular library provides Bootstrap 4 components for Angular. It provides high testing coverage and no 3rd party JS dependencies.
5. Onsen UI
At nearly 6k stars Onsen-UI is a popular library for hybrid and mobile web apps for Android and iOS using Javascript. Onsen-UI for Angular provides components with Material and Flat designs, with binding for Angular.
6. Vaadin Components
Bridging the gap between Angular components and Polymer elements, the Vaadin elements provide Material inspired UI components for mobile and desktop apps. Although elements are kept in different repos, they can be grouped into a single repo while kept individually available with Bit.
7. NG-ZORRO
Written in TypeScript with complete define types, the NG- ZORRO components aim to provide an enterprise-class UI based on Ant Design. At 2k stars, this Chinese-made library is an interesting option for web applications.
8. NG Lightning
Angular components built for the Saleforce Lightning Design System. These stateless functional components depend only on their input properties, to provide improved performance and enhanced flexibility.
9. NG Semantic-UI
Angular UI building blocks based on Semantic-UI. With 27 components and nearly 1k stars, this library makes the popular Semantic-UI interface available as a set of components for Angular applications.
10. Clarity
Clarity is an open source design system by VMware that brings together UX guidelines, an HTML/CSS framework, and Angular components. It provides a rich set of data-bound, performant components on top of Angular.
11. NG2 Charts
At over 1k stars, this library provides Angular directives for 6 different types of charts, with properties based on chart.js. This library can be useful for visualizing large data and lists.
Individual components
Individual Angular components can be found in the popular awesome-angular and awesome-angular-components projects. When working with individual components, you can also keep them organized in a common Bit Scope, to provide better discoverability and simpler maintenance. Then, they can be installed and updated across your different projects.
For more Information and build a website, Hire Angular Developer from us, as we give you high quality product by utilizing all the latest tools and advanced technology. E-mail us – hello@hkinfosoft.com or Skype us: “hkinfosoft“.
To develop custom web app using Angular, please visit our technology page.
- blog.bitsrc.io