Showing posts with label ORM. Show all posts
Showing posts with label ORM. Show all posts

Wednesday, September 9, 2020

Laravel 8 New Features

 Laravel 8 New Features

Laravel Jetstream

Laravel Jetstream is a beautifully designed application temporary structure for Laravel. Jetstream provides the main starting point for your next project and it includes login, registration, email verification, two-factor authentication, session management, API support via Laravel Sanctum, and optional team management. Laravel Jetstream replaces and improves upon the legacy authentication UI scaffolding available for previous versions of Laravel.

Models Directory

Now you can access all your models from new directory that's app/Models, instead of app folder all commands also default assumes that they get all the models from app/Models.

Model Factory Classes


Eloquent model factories have been entirely re-written as class based factories and improved to have first-class relationship support. For example, the UserFactory included with Laravel is written like so:

<?php

namespace Database\Factories;

use App\Models\User;
use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Str;

class UserFactory extends Factory
{
    /**
     * The name of the factory's corresponding model.
     *
     * @var string
     */
    protected $model = User::class;

    /**
     * Define the model's default state.
     *
     * @return array
     */
    public function definition()
    {
        return [
            'name' => $this->faker->name,
            'email' => $this->faker->unique()->safeEmail,
            'email_verified_at' => now(),
            'password' => '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', // password
            'remember_token' => Str::random(10),
        ];
    }
}
Thanks to the new HasFactory trait available on generated models, the model factory may be used like so:

use App\Models\User;

User::factory()->count(50)->create();

Since model factories are now simple PHP classes, state transformations may be written as class methods. In addition, you may add any other helper classes to your Eloquent model factory as needed.

For example, your User model might have a suspended state that modifies one of its default attribute values. You may define your state transformations using the base factory's state method. You may name your state method anything you like. After all, it's just a typical PHP method:

/**
 * Indicate that the user is suspended.
 *
 * @return \Illuminate\Database\Eloquent\Factories\Factory
 */
public function suspended()
{
    return $this->state([
        'account_status' => 'suspended',
    ]);
}
After defining the state transformation method, we may use it like so:
use App\Models\User;

User::factory()->count(5)->suspended()->create();

 As mentioned, Laravel 8's model factories contain first class support for relationships. So, assuming our User model has a posts relationship method, we may simply run the following code to generate a user with three posts:

$users = User::factory()
            ->hasPosts(3, [
                'published' => false,
            ])
            ->create();

Migration Squashing

As you build your application, you may accumulate more and more migrations over time. This can lead to your migration directory becoming bloated with potentially hundreds of migrations. If you would like, you may now "squash" your migrations into a single SQL file. To get started, execute the schema:dump command:

php artisan schema:dump

// Dump the current database schema and prune all existing migrations...
php artisan schema:dump --prune

 When you execute this command, Laravel will write a "schema" file to your database/schema directory. Now, when you attempt to migrate your database and no other migrations have been executed, Laravel will execute the schema file's SQL first. After executing the schema file's commands, Laravel will execute any remaining migrations that were not part of the schema dump.


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\Batch;
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 Rate Limiting

Laravel's request rate limiter feature has been augmented with more flexibility and power, while still maintaining backwards compatibility with previous release's throttle middleware API.

Rate limiters are defined using the RateLimiter facade's for method. The for method accepts a rate limiter name and a Closure that returns the limit configuration that should apply to routes that are assigned this rate limiter:
use Illuminate\Cache\RateLimiting\Limit;
use Illuminate\Support\Facades\RateLimiter;

RateLimiter::for('global', function (Request $request) {
    return Limit::perMinute(1000);
});
Since rate limiter callbacks receive the incoming HTTP request instance, you may build the appropriate rate limit dynamically based on the incoming request or authenticated user:
RateLimiter::for('uploads', function (Request $request) {
    return $request->user()->vipCustomer()
                ? Limit::none()
                : Limit::perMinute(100);
});

Sometimes you may wish to segment rate limits by some arbitrary value. For example, you may wish to allow users to access a given route 100 times per minute per IP address. To accomplish this, you may use the by method when building your rate limit:

RateLimiter::for('uploads', function (Request $request) {
    return $request->user()->vipCustomer()
                ? Limit::none()
                : Limit::perMinute(100)->by($request->ip());  });                    

 

Rate limiters may be attached to routes or route groups using the throttle middleware. The throttle middleware accepts the name of the rate limiter you wish to assign to the route:


Route::middleware(['throttle:uploads'])->group(function () {
    Route::post('/audio', function () {
        //
    });

    Route::post('/video', function () {
        //
    });
});

Closure Dispatch / Chain

Using the new catch method, you may now provide a Closure that should be executed if a queued Closure fails to complete successfully after exhausting all of your queue's configured retry attempts:

 

 use Throwable;

dispatch(function () use ($podcast) {
$podcast->publish(); })->catch(function (Throwable $e) { // This job has failed... });

Dynamic Blade Components

Sometimes you may need to render a component but not know which component should be rendered until runtime. In this situation, you may now use Laravel's built-in dynamic-component component to render the component based on a runtime value or variable:

<x-dynamic-component :component="$componentName" class="mt-4" />


Sunday, August 30, 2020

Laravel Eloquent

About the Eloquent Model

The PHP Laravel framework is coming with the Eloquent Object Relational Mapper (ORM), which provides an extremely easy way to communicate with a database. As developers need to create complex websites and other applications, they prefer easy coding with fast development. Laravel helps make development faster and provides an adequate solution to most problems encountered. Large business requirements are addressed with faster development, as well as well-organized, reusable, maintainable, and scalable code. It works with custom web applications as it comes up with multiple databases and performs common database operations in different languages.

How its work in our programing

Developers can work in Eloquent with multiple databases efficiently using an Active Method implementation. It is an architectural pattern where the model created in the Model-View-Controller (MVC) structure corresponds to a table in the database. The advantage is for models to perform common database operations without coding lengthy SQL queries. Models allow data querying in your tables, as well as inserting new records into tables. The process of synchronizing multiple databases running on different systems is simplified. There is no need to write SQL queries at all. All you have to do is to define database tables and relations between them, and Eloquent will do the rest of the job.

Migration

Migration is a process of to easily create a database table without an open database interface by writing PHP rather than SQL/MYSQL Code. Also, it provides a way of adding version control to your database. Assuming that our database is up and running. To get started with migrations, you need to setup Laravel migration. Open the terminal and choose the correct path, and you can use artisan to create that migration table with this command:

php artisan migrate:install

To create a new migration, just run the following command:

php artisan make:migration create_managers

This creates below the migration file. In your text editor, open the newly created file under the app/database/migration folder:

<?php
use IlluminateSupportFacadesSchema;
use IlluminateDatabaseSchemaBlueprint;
use IlluminateDatabaseMigrationsMigration;

class CreateManagersTable extends Migration
{
    /**
    * Run the migrations.
    *
    * @return void
    */
    public function up()
    {
        Schema::create('managers', function (Blueprint $table) {
            $table->increments('id');
            $table->timestamps();
        });
    }

    /**
    * Reverse the migrations.
    *
    * @return void
    */
    public function down()
    {
        Schema::dropIfExists('managers');
    }
}

The code is a class with the same name ‘managers’, and has two methods: up and down. The up method should make changes to the database; so whenever you migrate your database, whatever code is in the up method will be run. On the other hand, the down method should revert those changes to the database; so whenever you rollback your migration, the down method should undo what the up method did. Inside the up method is the schema builder that is used to create and manipulate tables. What will happen if you undo some of your migrations? All you have to do is to implement the following command:


php artisan migrate:rollback

And it will retract the last migration that was being implemented. Also, you can completely reset the database by running:

php artisan migrate:reset

This will undo all your migrations.

Defining Eloquent models

After you are done with the migration of your database, the next process is the seeding. Eloquent comes into the picture since seeding is inserting records into our database. Thus you will need to create your models before you can seed the database. Each database table has a corresponding model that is used to interact with that table. Models allow you to query for data in your tables, as well as insert new records into the table. The easiest way to create a model instance is using the following command:

php artisan make:model Manager

An example of a Manager model is shown below, which can be used to retrieve and store information from our students database table:

<?php
namespace App;
use IlluminateDatabaseEloquentModel;

class Manager extends Model
{
    //
}


When you generate a model and at the same time you want to generate a database migration, you can either use the –migration or -m option:

php artisan make:model Manager --migration

php artisan make:model Manager -m

Seeders

Many get confused  and think its too complex to create for seeders but it is simply a class that populates your database. The good thing with seeders is that they can be executed using a simple command to refresh your database. It helps create proper data in newly created database instead of sample data.

The basic idea behind seeders is to help the problem of “dirty data” where one can develop a simple or even a powerful seeder. Overall seeders are a special set of classes that allow us to populate our database over and over with the same exact data. Let’s implement the following command:

php artisan make:seeder ManagersRecordSeeder

In the text editor, under the seeds folder, open the newly created file with filename: ManagersRecordSeeder.php. As you can see, this is just a very simple class with a single method called run().

<?php
use IlluminateDatabaseSeeder;

class ManagersRecordSeeder extends Seeder
{
    /**
    * Run the database seeds
    * @return void
    */

    public function run()
    {
        //
    }
}

The code is just a wrapper around a Console Command class, made specifically to help with the seeding task. Modify the code and then save it.

public function run()
{
    echo 'Seeding!';
}
And, will go back to the terminal:

php artisan db:seed --class=ManagersRecordSeeder

This is just purely calling the DB facade, but keep in mind that there’s no actual database interaction here. You can now populate the table with a few entries and run:

php artisan db:seed --class=class=ManagersRecordSeeder

Here you can keep deleting, adding, editing entries while you work, and then reset them with a simple command.

CRUD with Eloquent

CRUD operations under the Eloquent object-relational mapper (ORM) make it easier for Laravel developers to work with multiple databases. It performs create, retrieve, update, and delete (CRUD) operations, as well as maps object models to database tables. It handles all the database interaction required for CRUD operations.

Creating records

You can use the ::create method to insert a new record in the database.

manager_record::create(array(
    'first_name' => 'Michel',
    'last_name'  => 'Hokings',
    'manager_rank' => 1
));

Aside from the simple create method shown above, you can also create a new object and assign different attributes to it. Then, you can call the save() function and execute the code. Methods such as firstOrCreate() or firstOrNew() are other options for creating records. These will enable finding a student with certain attributes; if that student is not found, then you will either create it in the database or instantiate a new instance.

Retrieving records

Using Eloquent ORM, getting and finding records from the database is manageable and easy. The queries are simply built and offer a smooth flow. For creating ::where statements, you will use get() and first() methods. The first() method will return only one record, while the get() method will return an array of records that you can loop over. Also the find() method can be used with an array of primary keys, which will return a collection of matching records. Here are some few examples:

$manaer = Managers::all();

This code gets all the managers. While the code below, finds a specific manager by id:

$manager = Managers::find(1);

Also, as shown below, the code describes to find a manager based on specific attribute.

$michel = Managers::where('name', '=', 'Michel')->first();

For the get() method, this code shows how to find a manager with a rank level greater than 5.

$rankManagers = Managers::where('manager_rank', '>', 5)->get();

Updating records

Updating records using Eloquent is as easy. To update a record, just find the record you would like to update, change the attributes, and save. For example, to change the manager rank level of John Doe to 5, first find the manager and then execute the save method.

$MichelHokings = Bear::where('name', '=', 'Michel')->first();
$MichelHokings->danger_level = 5;
$MichelHokings->save();

The save method may also be used to update models that already exist in the database.

Deleting records

Eloquent boasts its easy process of updating records, but it has the same story with deleting. There are two options: record pull-out and execute delete method, or simply use the destroy method. To find and delete a record, simply execute the following commands:

$manager = Managers::find(1);
$manager->delete();

To delete a record and multiple records, the commands are executed:

Managers::destroy(1);
Managers::destroy(1, 2, 3);

Please note that the parameters of destroy are primary keys only unlike the delete method which can accept any database column.

To find and delete all managers with rank level that is greater than 10.

Managers::where('manager_rank', '>', 10)->delete();

Writing a web application in PHP, developers have the option to choose from a rich list of PHP frameworks. The ongoing demand combined with several usage statistics posted from communities suggest that Laravel is currently more popular than other PHP frameworks. However, seasoned web developers never choose a PHP framework based on its popularity or hype. There are pros and cons to consider. A lot of developers tend to downplay the popularity of PHP, but keep in mind that you must choose a PHP framework that fits all the project requirements. Also as a developer, it is important to use a PHP framework, as Laravel helps you reduce web application development cost.

The robust features and tools provided by Eloquent inside Laravel make it easier for developers to build custom web applications following specified business requirements. This article has given you a primer on how to use the basic features of Eloquent ORM. Keep in mind that some features often impact the performance of any Laravel application. Hence you have to implement a number of performance optimization techniques to boost the application’s speed and user experience. But Laravel has been evolving consistently to meet emerging web application development trends. You can always accelerate custom web application development by using the new features and enhancements included in the latest version of Laravel. Learn more about Eloquent and Laravel through its detailed documentation.

In a very competitive world of custom web applications, the health and well-being of the application are synonymous with business. This article discussed how Eloquent efficiently provide an effortless way to communicate with a database. The SQL queries from your application to the database are very critical. For example, a company may have a standard concerning the SQL query execution time. If a query is above 50 ms and according to their standard that is considered a slow query then a developer needs to perform optimization of the query as soon as possible. Time is very critical in this scenario, so a developer needs help in finding where and what causes the slow query. Thus Retrace can truly help developers by answering the where and what questions.

Slow queries can be tracked in milliseconds under the Took (ms) column and each duration is accompanied by the Web Requests. Thus when a slow query is detected, its corresponding attributes are directly pinpointed.

Conclusion

PHP is a powerful language. Laravel is considered a famous and robust PHP framework. Laravel with Eloquent provides competitive technology for web applications. Also Retrace is a powerful tool for tracing performance of applications built in PHP. It provides an efficient way of tracking SQL queries. Not just tracking, but providing information on specific queries provides a lot more help to developers.

Integration of Queue in Laravel

Integration of Queue in Laravel Introduction Laravel Queue is to enhances the laravel application performance and provides a smooth proc...