Building Efficient Applications with MySQL Stored Procedures

https://kongulov.dev/assets/images/posts/building-efficient-applications-with-mysql-stored-procedures.png

Building Efficient Applications with MySQL Stored Procedures

MySQL stored procedure is a powerful database function that allows you to store and execute a set of SQL statements in the database, similar to functions in programming. The storage process can greatly improve the performance, security and maintainability of the database. This article will introduce the use of MySQL stored procedures in detail.

What is a MySQL stored procedure?

MySQL stored procedures are a set of precompiled SQL statements that are stored in the database with a name and can be called and executed at any time. Stored procedures can accept input arguments, perform a series of operations, and return results. These characteristics make stored procedures an ideal tool for handling complex queries, data manipulation, and transaction management.

Create a stored procedure

To create a MySQL stored procedure, you use CREATE PROCEDURE statements. Here is a simple example:

DELIMITER //
CREATE PROCEDURE GetUser(IN user_id INT)
BEGIN
    SELECT * FROM users WHERE id = user_id;
END //
DELIMITER ;
  • DELIMITERU sed to define the separator. Because the stored procedure contains multiple SQL statements, a separator different from the semicolon is required.
  • CREATE PROCEDURE Create a stored procedure that accepts an user_id input argument named and contains a set of SQL statements between BEGIN and END

Call stored procedure

Once the stored procedure is created, you can CALL execute it using the statement:

This will call the stored procedure named and pass it GetUser the arguments 1

Arguments to stored procedure

Stored procedures can accept arguments, which can be input arguments, output arguments, or input/output arguments. In the above example, user_id it is an input argument because it is used to pass values to the stored procedure. You can define different types of arguments using the following syntax:

  • IN: Indicates that the argument is an input argument and can be used to pass values to the stored procedure.
  • OUT: Indicates that the argument is an output argument and can be used to return a value from a stored procedure.
  • INOUT: Indicates that the argument is an input/output argument and can be used to pass values and return values from stored procedures.

Stored procedure logic

The body of the stored procedure is contained BEGIN between END and and can contain various SQL statements, such as SELECT, INSERT, UPDATE, DELETE, IF statement, LOOP statement, etc. This allows you to perform complex logic in stored procedures, such as transaction processing, conditional judgments, and loop operations.

Advantages of the storage process

Using stored procedures has the following advantages:

  1. Performance Optimization: Stored procedures are generally faster than individual SQL statements because they are compiled and cached on the database server, reducing communication overhead.
  2. Security: Stored procedures can be used to encapsulate sensitive operations, thereby improving the security of the database. The user only needs to call the stored procedure without directly accessing the table.
  3. Maintainability: Stored procedures allow commonly used business logic to be encapsulated in one place, reducing program code redundancy and making it easier to maintain.
  4. Transaction management: Stored procedures can be used to manage complex transaction logic to ensure data consistency and integrity.
  5. Reduce network latency: The storage process is executed on the database server, which can reduce network communication with the user.

Disadvantages of storage process

While the storage process has many advantages, there are also some disadvantages:

  1. Complexity: Writing and maintaining complex stored procedures can become difficult, especially for developers who are unfamiliar with stored procedures.
  2. Portability: The syntax and functionality of stored procedures vary between database systems and may not be portable enough.
  3. Difficult to debug: Debugging stored procedures can be more challenging than debugging application code because they execute in a database.

Modify and delete stored procedures

To modify a stored procedure, you use ALTER PROCEDURE statements. To delete a stored procedure, you can use DROP PROCEDURE the statement.

These commands allow you to update the logic of a stored procedure or delete a stored procedure that is no longer needed.

Conclusion

MySQL stored procedures are a powerful tool that can improve the performance and security of the database, but they also need to be used with caution to ensure good code quality and maintainability. Stored procedures are often used to encapsulate complex business logic, optimize queries, and provide better database management and security. Whether you are processing large-scale data or performing complex transactions, stored procedures are a powerful tool for MySQL database management.

Laravel News Links

Query Builder – Where method the full guide

https://ahmedash.dev/images/thumbs/laravel/laravel-where.png

Introduction

The simples way to use where is just to statically call it on your model as Model::where('name', 'Ahmed')->first()

Laravel Query builder is very powerful. It offers a rich set of methods that makes it easy for you to write SQL queries in a very easy way.

One of those methods is the Where method and it has many ways to simplify complex queries

The Query Builder

First of all, you need to understand that where and all its siblings lives in the Builder class. and when you call a static method on the model directory. Most of the times, it will be forwarded to the Eloquent query builder

1public static function __callStatic($method, $parameters)
2{
3    return (new static)->$method(...$parameters);
4}
 1public function __call($method, $parameters)
 2{
 3    if (in_array($method, ['increment', 'decrement', 'incrementQuietly', 'decrementQuietly'])) {
 4        return $this->$method(...$parameters);
 5    }
 6
 7    if ($resolver = $this->relationResolver(static::class, $method)) {
 8        return $resolver($this);
 9    }
10
11    if (Str::startsWith($method, 'through') &&
12        method_exists($this, $relationMethod = Str::of($method)->after('through')->lcfirst()->toString())) {
13        return $this->through($relationMethod);
14    }
15
16    return $this->forwardCallTo($this->newQuery(), $method, $parameters);
17}

The forwardCallTo, forwards the method call to the $this->newQuery() which returns an instance of Builder class

1/**
2 * Get a new query builder for the model's table.
3 *
4 * @return \Illuminate\Database\Eloquent\Builder
5 */
6public function newQuery()
7{
8    return $this->registerGlobalScopes($this->newQueryWithoutScopes());
9}

So by looking into the where method in the Builder class. it’s about 100 lines
. That’s because it can handle many cases. So let’s take them one by one

Simple where condition

The first easy simple way to write a condition in laravel is to just pass the key and value to the where.

1User::where('email', 'root@admin.com')->first()

This will translate to

1SELECT * FROM users WHERE `email` = 'root@admin.com' LIMIT 1

Multiple where

Chain wheres

You can also chain several wheres

1User::where('email', 'root@admin.com')
2	->where('is_active', true)->first()

This will translate to

1SELECT * FROM users WHERE `email` = 'root@admin.com' AND `is_active` = true LIMIT 1

Array of Wheres

Another way to do so is to use an array of where

1User::where([
2	'email' => 'root@admin.com',
3	'is_active' => true
4])->first()

This will translate to

1SELECT * FROM users WHERE `email` = 'root@admin.com' AND `is_active` = true LIMIT 1

Using OrWhere

The OrWhere method is used to add an OR constraint to your queries. It functions similarly to the where method, but adds the condition as an “OR” clause rather than an “AND” clause.

1User::where('email', 'root@admin.com')
2	->orWhere('username', 'admin')->first()

But how we do the is_active when we use OR?

Grouped Conditions

We can use grouped conditions by passing a closure to the where method

1User::where(function($q) {
2  $q->where('email', 'root@admin.com')
3	  ->orWhere('username', 'admin');
4})
5->where('is_active', true)
6->first()

And this will translate to

1SELECT
2*
3FROM `users`
4WHERE (`email` = 'root@admin.com' or `username` = 'admin')
5AND `is_active` = 1
6
7LIMIT 1

And you can have as many nested groupings as you want

When and Where

You can also apply specific wheres only when a condition is true

1$onlyActive = true;
2
3User::where('email', 'root@admin.com')
4->when($onlyActive, function($q) {
5	$q->where('is_active', true);
6})->first()

The where is_active = true will be only applied if the $onlyActive is true

Shortcuts

There are also some shortcuts that can be applied to simplify how you write eloquent

Where{Column}

1User::whereEmail('root@admin.com')->first()

Translates to

1SELECT * FROM `users` WHERE `email` = 'root@admin.com' LIMIT 1

Where{Column}And{Column}

1User::whereEmailAndStatus('root@admin.com','active')->first()

Translates to

1SELECT * FROM `users` WHERE `email` = 'root@admin.com' AND `status` = 'active' LIMIT 1

Where{Column}Or{Column}

1User::whereEmailOrUserName('root@admin.com','admin')->first()

Translates to

1SELECT * FROM `users` WHERE `email` = 'root@admin.com' OR `user_name` = 'admin' LIMIT 1

WhereNull

You can also look for records where the column value is null

1User::whereNull('confirmed_at')->get()
1SELECT * FROM `users` WHERE `confirmed_at` IS NULL

WhereNot

There is also WhereNot to apply “NOT EQUAL TO” condition in your queries.

1User::whereNot('status','active')->all()

Which translates to

1SELECT * FROM `users` WHERE NOT `status` = 'active'

WhereNotNull

A combination of the previous two

1User::whereNotNull('confirmed_at')->all()

Which translates to

1SELECT * FROM `users` WHERE `confiremd_at` IS NOT NULL

Conclusion

We checked together what are the possible ways to use the where method. Let me know if you have any tips or tricks or maybe missed cases I did not cover in the comments.

Laravel News Links

A James Bond "movie" I’d never heard of before

http://img.youtube.com/vi/yH8mVTDylXI/0.jpg

 

I wasn’t aware that, according to Wikipedia:

To promote the film ["You Only Live Twice"], United Artists Television produced a one-hour colour television programme titled Welcome to Japan, Mr. Bond, which first aired on 2 June 1967 in the United States on NBC. Bond regulars Lois Maxwell and Desmond Llewelyn appeared, playing respectively Miss Moneypenny and Q. Kate O’Mara appears as Miss Moneypenny’s assistant. The programme shows clips from You Only Live Twice and the then four existing Bond films, and contained a storyline of Moneypenny trying to establish the identity of Bond’s bride.

The James Bond Wiki notes:

The feature stars Lois Maxwell and Desmond Llewelyn in character as Miss Moneypenny and Q respectively as well as Kate O’Mara as Miss Moneypenny’s unnamed assistant. They all reflect on James Bond’s previous adventures in Dr. No, From Russia with Love, Goldfinger and Thunderball through the use of archival footage. In addition they speculate on Bond’s current and future assignments, showing preview clips of You Only Live Twice.

A subplot is included about a woman (who is never directly shown, akin to Ernst Stavro Blofeld) who is obsessed with becoming Bond’s next lover. She is seen holding a Pan paperback copy of On Her Majesty’s Secret Service, possibly as a teaser to the audience that it would be the next novel to be adapted into a film (which it was).

Fortunately for us, the entire TV special is available on YouTube.  Enjoy!

It’s a bit dated, of course, compared to modern high-tech gee-whiz Bond movies, but I still enjoyed it – and it stars Sean Connery, who as far as I’m concerned is still the best of the actors who played Bond.

Peter

Bayou Renaissance Man

The 10 Best YouTube Channels to Learn Graphic Design

https://static1.makeuseofimages.com/wordpress/wp-content/uploads/2023/09/black-flat-screen-tv-turned-on-displaying-design.jpg

Graphic design is a creative means to convey or sell ideas to any audience. Whether creating logos for your business, designing a website for a client, or making posters for an event, the art and the skill remain crucial in today’s digital world.

However, learning graphic design can be tricky because, without guidance, you may end up spending on books, courses, or software that offer little to no help. Fortunately, YouTube provides a free solution to this, and in this article, we’ll share the best YouTube channels to learn graphic design.

Being the official YouTube channel for Adobe Photoshop, this channel was created to help people learn and become adept at digital imaging using Adobe Photoshop. Offering valuable resources to over 760,000 subscribers, you’re certain to hone your graphic design skills with Adobe Photoshop.

The channel lists various videos that cover a wide range of graphic design topics. These videos teach viewers how to use Photoshop to achieve impressive results, from removing unwanted objects to changing a person’s hair color in Photoshop. Additionally, they keep viewers informed on the latest software features and how to use them.

The channel also showcases interviews and stories from professional graphic designers in various fields. Witnessing the creative process of these photographers, illustrators, and animators is something not to be missed, as it can fast-track your design journey.

If you’ve ever wanted to learn how to create striking logos, then this is the channel for you. Will Paterson is a freelance graphic designer and content creator who runs his own YouTube channel. Specializing in logo design and hand lettering, Will has worked with reputable brands and now shares his knowledge to make graphic design easier.

Not only are Will’s videos informative, but they are also entertaining, giving you a glimpse into Will’s creative mind. You can learn how to design logos, gain insight from logo critiques, and even participate in design competitions.

In addition, Will makes creative bite-sized videos to help steer his audience in the right direction to bolster their careers. Will’s YouTube Shorts can range from locating graphic design clients to mastering pen tools for graphic design. You can check out his Behance and Dribble portfolios to see the designs in his arsenal.

Design with Canva is a popular YouTube channel run by Ronny and Diana—two Canva experts and certified educators. This channel helps people learn how to use Canva, an online graphic design platform, to create designs for their business or personal projects.

In their videos, Ronny and Diana share tips, tricks, tutorials, and reviews of Canva features and tools. Furthermore, they cover other design-related topics such as artificial intelligence, chatbots, and video editing.

Their videos offer more than just theoretical knowledge—they provide practical, actionable tips that viewers can use in their projects. Moreover, the channel provides free customizable YouTube channel art templates and a YouTube banner maker with attractive, aesthetic layouts.

The Tutvid YouTube channel is a helpful resource for learning about Adobe software. Nathaniel Dodson, a content creator and graphic designer, hosts the channel with over 1.2 million subscribers.

Nathaniel’s videos cover software such as Photoshop, Illustrator, and XD, and teach viewers how to use these tools for improved designs. The videos suit beginners and advanced users, covering topics like layers, masks, filters, fonts, and other design elements.

Additionally, Tutvid covers the latest features and updates of Adobe software, such as using neural filters or replacing complex skies in Photoshop. Following his videos, you can learn a lot about Adobe software and become a pro.

Yes I’m a Designer offers an extensive collection of over 600 free tutorials, making it one of the top graphic design channels available. The channel is led by Martin Perhiniak, a skilled Adobe design instructor with an impressive portfolio, including projects like Cars and Toy Story. Martin has a wealth of knowledge and teaches design principles and best practices from experience as a designer and retoucher.

If you’re interested in the latest generative AI features or vectorizing images in Adobe Illustrator, you’ll find tons of information on this channel.

In addition to the tutorials, the channel provides a website, Yes I’m a Designer, that offers more resources and quizzes to test your knowledge and help you practice what you’ve learned. Upon completion, you can receive certificates for your achievements to boost your credibility and portfolio.

The CorelDRAW YouTube channel is great for anyone looking to improve their skills with the CorelDRAW Graphics Suite. With more than 130,000 subscribers and over 900 videos available, there are numerous resources to help you upskill.

The channel provides diverse tutorials on various topics, including illustration, photo editing, custom CorelDRAW color palettes, and multipage layout. Additionally, you can watch speed drawing videos where skilled designers utilize the CorelDRAW Graphics Suite to bring their designs to life.

A series of quick how-to videos show you practical steps to perform simple tasks in a few minutes. Besides design tutorials, you also get videos that show you how to collaborate in CorelDRAW and use it to its maximum functionality.

Dansky is a talented designer, instructor, content creator, and host of an incredible channel dedicated to sharing his vast design knowledge. With more than 850,000 subscribers, this channel is one of the best resources for learning graphic design.

Dansky covers a wide range of design applications, including Photoshop, InDesign, Adobe XD, and After Effects. Additionally, he offers a series where he reviews his subscribers’ design work, providing constructive feedback and useful tips. This lets you examine your design with a skilled professional and get helpful tips for improvement.

Overall, Dansky’s videos are informative and engaging, providing an interactive learning experience.

If you’re interested in using Affinity Photo, Affinity Designer, or Affinity Publisher, the Affinity Revolution YouTube channel is an excellent resource. Ally, the channel’s creator, has been sharing her expertise in using these powerful and affordable programs since 2016. With a degree in education and a passion for creativity, Ally has helped thousands of people learn how to use Affinity software.

You can watch her Affinity Photo tutorials to learn how to remove backgrounds, tweak color grades, and make perfect selections. You can also follow her Affinity Designer and Publisher tutorials to expand your skills even further.

Gareth David Studio is a YouTube channel with videos that motivate and teach graphic design enthusiasts. It is managed by Gareth David, a professional graphic designer, logo, and visual brand specialist with over 14 years of experience in the industry.

The channel features a range of series and courses, including logo design, poster design, and brand identity. Additionally, it has a resource library that includes downloadable files and links to helpful websites and books for your perusal and further knowledge.

Moreover, its beginner’s guide and design Q&A sections offer insight into basic graphics design concepts and popular questions. With these videos, you can develop a solid foundation in design and chart your path more easily.

Tom Cargill is a UK-based graphic designer and illustrator who runs Satori Graphics, a channel dedicated to teaching graphic design. With an impressive 1.2 million subscribers and over 71 million views, Satori Graphics is one of the leading channels for learning graphic design.

The channel offers a variety of series and courses, such as the logo design process. This popular series guides learners through the process of creating logos for different clients with diverse needs. Additionally, the typography design series showcases the creation of various typography designs using Adobe Illustrator and Photoshop.

Learn From Professionals in the Design Industry

Learning from professionals and observing their design process is one of the best ways to grow as a graphic designer. Luckily, several online resources and courses are dedicated to graphic design, and YouTube is a good place to begin your journey. Keep learning and sharpening your skills, and you’ll become a pro in no time.

MakeUseOf

Mapping Sci-Fi Locations in Real Space

https://theawesomer.com/photos/2023/09/mapping_sci_fi_locations_in_space_t.jpg

Mapping Sci-Fi Locations in Real Space

Link

Science fiction books, TV shows, and movies often set their stories in real locations in space. The Overview Effect put together a visualization that charts the relative locations of stories in fictional works like Star Trek and Alien, and Dune, using actual places in the universe to illustrate their distances and relationships.

The Awesomer

Mapping Sci-Fi Locations in Real Space

https://theawesomer.com/photos/2023/09/mapping_sci_fi_locations_in_space_t.jpg

Mapping Sci-Fi Locations in Real Space

Link

Science fiction books, TV shows, and movies often set their stories in real locations in space. The Overview Effect put together a visualization that charts the relative locations of stories in fictional works like Star Trek and Alien, and Dune, using actual places in the universe to illustrate their distances and relationships.

The Awesomer

How to Use FreedomGPT to Install Free ChatGPT Alternatives Locally on Your Computer

https://i.kinja-img.com/gawker-media/image/upload/c_fill,f_auto,fl_progressive,g_center,h_675,pg_1,q_80,w_1200/9ddb7f2adc0fe8bb0feb3673ef11a842.jpg

The number of ways you can chat with generative AI engines continues to grow, from ChatGPT to Claude to Google Bard to Bing AI, and FreedomGPT is one of the latest options you can add to your list of potential conversational partners. Here we’re going to take you through the key features that mark it out as being a little different and show you what it’s like to use.

Why is Everyone Suing AI Companies? | Future Tech

There are two main reasons you might want to use FreedomGPT: First, it can run locally on your computer, without any internet access. Second, it’s completely uncensored, which may or may not be an advantage depending on where in the world you live, the restrictions placed on your web access, and what you want out of your AI bots.

FreedomGPT wants to offer something different.
Screenshot: FreedomGPT

In other words, the engine will produce some very controversial takes if prompted in the right way, and you should be prepared for that if you’re going to make use of it. As you may have noticed, ChatGPT will refuse to answer certain categories of questions—covering areas such as financial advice or illegal activities—but FreedomGPT has no such qualms.

It’s also free to use at this point, which combined with the local installation option, may make it worth your while to at least try out. There is a web version available too, which confusingly deals with a different set of AI models and can’t be accessed for free, but it’s the downloadable version that we’re going to be focusing on here.

You can set up FreedomGPT on your computer by heading to the FreedomGPT website and following the link for either the Windows or the macOS download. You’ll then be asked to pick the AI model you want to use with FreedomGPT, and whether you want the full (and slower) version or the fast (and less complete) version of the model.

You’ve got a selection of language models to pick from.
Screenshot: FreedomGPT

Your two options are LLaMA, as released publicly by Meta, and Alpaca, a version of LLaMA fine-tuned by Stanford researchers which is more ChatGPT-like in its behavior. You’ll also be shown the download size for each model, and the amount of RAM you need on your local machine.

With the downloading and the installing out of the way, you’re free to start experimenting with FreedomGPT on your Windows or macOS machine. We’ll give you a few ideas here for how you can use the software while staying well away from anything ethically or legally dubious—prompts that ChatGPT would flat-out refuse to respond to.

Using FreedomGPT

FreedomGPT will open up with a ChatGPT-style interface, but at the moment it’s not quite as friendly as the OpenAI-developed alternative. All of your chats are bunched together in the same conversation, and to start again from scratch you need to close down and restart the app, or choose View and Reload from the menus at the top.

At that point, all of your existing chats will be lost for good, and the AI bot isn’t great at remembering what you’ve already said to it either, which means it’s best suited for standalone questions rather than ongoing chats. These aren’t necessarily dealbreakers when it comes to using FreedomGPT, but it’s important to be aware of its limitations.

FreedomGPT works in a similar way to other AI bots.
Screenshot: FreedomGPT

Up in the top left of the interface, you can switch between the different AI models on offer, and download any that aren’t currently stored on your computer. You’ll also find links to the program’s Discord and GitHub locations online, and these are your best bets for getting help and support with FreedomGPT.

You can interact with FreedomGPT in all the ways you’ll be familiar with from other AI bots: Get explainers on difficult concepts, get ideas for particular projects and activities, hear the pros and cons of a decision you’re weighing up, set up outlines for research that you’re undertaking and so on. It’ll write poetry, come up with idea prompts, and take instructions about the style and tone of its responses.

We didn’t notice too much of a difference between the LLaMA and the Alpaca models, although the latter seemed more comprehensive and more conversational a lot of the time. You can switch between models in the same conversation if you need to, although the program doesn’t leave behind any indication of which model has answered which conversation, which can get confusing.

You can switch between models in the same conversation.
Screenshot: FreedomGPT

It’s worth bearing in mind that the offline mode offered by FreedomGPT does offer you certain protections in terms of privacy and not having your conversations monitored, which is something you need to be wary about when using other similar services. We tested FreedomGPT in fully offline mode and can confirm it works as normal—the benefit of having everything installed locally.

In the AI gold rush that we’re currently living through, it’s not clear exactly who the winners and the losers are going to be, but FreedomGPT certainly offers something different for the time being—and if you’ve got more than a passing interest in what AI can offer, it’s something to try out.

Gizmodo

Cut & Paste a User Creation Statement with MySQL 8

https://i0.wp.com/lefred.be/wp-content/uploads/2023/09/Selection_533-1.png?w=914&ssl=1

Sometimes it’s convenient to retrieve the user creation statement and to copy it to another server.

However, with the new authentication method used as default since MySQL 8.0, caching_sha2_password, this can become a nightmare as the output is binary and some bytes can be hidden or decoded differently depending of the terminal and font used.

Let’s have a look:

If we cut the create user statement and paste it into another server what will happen ?

We can see that we get the following error:

ERROR: 1827 (HY000): The password hash doesn't have the expected format.

How could we deal with that ?

The solution to be able to cut & paste the authentication string without having any issue, if to change it as a binary representation (hexadecimal) like this:

And then replace the value in the user create statement:

The user creation succeeded, and now let’s test to connect to this second server using the same credentials:

Using MySQL Shell Plugins

I’ve updated the MySQL Shell Plugins available on GitHub to use the same technique to be able to cut & paste the user creation and the grants:

And for MySQL HeatWave on OCI ?

Can we use the generated user creation statement and grants with MySQL HeatWave ?

For the user creation, there is no problem and it will work. However for the grants there is a limitation as some of the grants are not compatible or allowed within MySQL HeatWave.

The list of grants allowed in HeatWave is available on this page.

Let’s try:

As you can see, some of the privileges are not allowed and the GRANT statements fail.

You have the possibility to ask to the MySQL Shell Plugin to strip the incompatible privileges, using the option ocimds=True:

Now you can use the generated SQL statements with a MySQL HeatWave instance:

Conclusion

As you can see, the default authentication plugin for MySQL 8.0 and 8.1 is more secure but can be complicated to cut and paste. But as we say, “if there is no solution, there is no problem !”, and in this case we have also a solution to copy and paste the authentication string.

Enjoy MySQL !

Planet MySQL

Pagination Laravel : Display continuous numbering of elements per page


A tutorial for displaying continuous numbering of collection items on all pagination pages in a Laravel project.

🌍 The French version of this publication : Pagination Laravel : Afficher une numérotation continue des éléments par page

Pagination in Laravel is a mechanism for dividing data into several pages to facilitate presentation and navigation when there are a large number of results.

Let’s consider a collection of publications or $posts that we retrieve and paginate in the controller’s index method to display 100 per page:

public function index()
{
    $posts = Post::paginate(100);
    return view("posts.index", compact('posts'));
}

On the view resources/views/posts/index.blade.php we can display 100 posts per page and present the links of the different pages of the pagination like this:

@extends('layouts.app')
@section('content')
<table>
        <thead>
            <tr>
                <th>No.</th>
                <th>Title</th>
            </tr>
        </thead>
        <tbody>
            @foreach ($posts as $post)
            <tr>
                <td></td>
                <td></td>
            </tr>
            @endforeach
        </tbody>
    </table>
    
    
    
@endsection

In this source code, $loop->iteration displays the iteration number inside the loop and $posts->links() displays the pagination links.

But notice, for each individual page the iteration starts at 1. This means that if we’re on page 2, the first iteration of that page will be considered the first iteration in the whole pagination.

If we want to display continuous numbering on all pages of a pagination, we can combine the number of elements per page, the current page number and the current iteration:

@foreach ($posts as $post)
<tr>
    <td></td>
    <td></td>
</tr>
@endforeach

In this source code we have :

  • $posts->perPage() : number of elements per page
  • $posts->currentPage() : current page number

By multiplying the number of elements per page by the current page number minus one, we obtain the starting index for that page. By adding $loop->iteration, we obtain the continuous index for each element of the paginated collection.

So even if you go from page 1 to page 2, the numbering continues from the last index on the previous page.

Take care! 😎

Laravel News Links

Unlocking Real-Time with WebSockets in Laravel with Soketi

https://fajarwz.com/blog/unlocking-real-time-with-websockets-in-laravel-with-soketi/featured-image_hu30557a156be601fd3510404f00108f87_1133773_1200x630_fill_q75_bgffffff_box_smart1_3.jpg

Imagine creating web applications that respond instantly, where data updates and interactions happen in the blink of an eye. Welcome to the world of real-time web development. In this article, we’ll try to create a simple example of how to use WebSocket connection in Laravel application using Soketi.

We’ll introduce Soketi, set up the necessary tools, and configure Laravel to work with WebSockets. By the end of this article, you’ll have a basic WebSocket system ready to go.

What is Soketi?

Soketi is a simple, fast, and resilient open-source WebSockets server. It simplifies the WebSocket setup process, allowing you to focus on building real-time features without the complexities of WebSocket server management.

Installation

You can read more about Soketi installation instructions in the Soketi official docs.

Before installing the CLI Soketi WebSockets server, make sure you have the required tools:

  • Python 3.x
  • GIT
  • The gcc compiler and the dependencies for build

Read more here about CLI installation here.

Step 1: Install Soketi

Begin by installing Soketi globally via npm. Open your terminal and run the following command:

npm install -g @soketi/soketi

This command will install Soketi on your system, allowing you to run it from the command line.

Step 2: Start Soketi Server

With Soketi installed, start the WebSocket server using this command:

Soketi will now serve as the WebSocket server for your Laravel application.

Step 3: Install Required Packages

We’ll use the Pusher protocol with Soketi. The pusher/pusher-php-server library provides a PHP interface for the Pusher API, which allows you to send and receive messages from Pusher channels.

composer require pusher/pusher-php-server

For receiving events on the client-side, you’ll also need to install two packages using NPM:

npm install --save-dev laravel-echo pusher-js

These steps will set us up for seamless real-time communication in our Laravel application.

Step 4: Configure Broadcasting

Next, configure broadcasting in Laravel. Open the config/broadcasting.php file and add or modify the Pusher configuration as follows:

'connections' => [

        'pusher' => [
            'driver' => 'pusher',
            'key' => env('PUSHER_APP_KEY'),
            'secret' => env('PUSHER_APP_SECRET'),
            'app_id' => env('PUSHER_APP_ID'),
            'options' => [
                'cluster' => env('PUSHER_APP_CLUSTER'),
                'host' => env('PUSHER_HOST') ?: 'api-'.env('PUSHER_APP_CLUSTER', 'mt1').'.pusher.com',
                'port' => env('PUSHER_PORT', 443),
                'scheme' => env('PUSHER_SCHEME', 'https'),
                'encrypted' => true,
                'useTLS' => env('PUSHER_SCHEME', 'https') === 'https',
            ],
            'client_options' => [
                // Guzzle client options: https://docs.guzzlephp.org/en/stable/request-options.html
            ],
        ],
        // ...

This configuration sets up Pusher as the broadcasting driver for WebSockets.

Read also:

Step 5: Set Environment Variables

Now, configure the Pusher environment variables in your .env file. Replace the placeholders with your Pusher credentials:

BROADCAST_DRIVER=pusher

# other keys ...

PUSHER_APP_ID=app-id
PUSHER_APP_KEY=app-key
PUSHER_APP_SECRET=app-secret
PUSHER_HOST=127.0.0.1
PUSHER_PORT=6001
PUSHER_SCHEME=http
PUSHER_APP_CLUSTER=mt1

VITE_APP_NAME="${APP_NAME}"
VITE_PUSHER_APP_KEY="${PUSHER_APP_KEY}"
VITE_PUSHER_HOST="${PUSHER_HOST}"
VITE_PUSHER_PORT="${PUSHER_PORT}"
VITE_PUSHER_SCHEME="${PUSHER_SCHEME}"
VITE_PUSHER_APP_CLUSTER="${PUSHER_APP_CLUSTER}"

These variables are essential for Laravel to connect to the WebSocket server.

By default, when we start the Soketi server without additional configuration, it will run on 127.0.0.1:6001 and use the following application credentials:

  • App ID: app-id
  • App Key: app-key
  • Secret: app-secret

These credentials play a crucial role in authenticating your frontend and backend applications, enabling them to send and receive real-time messages. It’s important to note that for production use, you should strongly consider changing these default settings to enhance security and ensure the smooth operation of Soketi.

Step 6: Configure JavaScript for Laravel Echo

In your JavaScript file (typically resources/js/bootstrap.js), configure Laravel Echo to use Pusher:

import Echo from 'laravel-echo';

import Pusher from 'pusher-js';
window.Pusher = Pusher;

window.Echo = new Echo({
    broadcaster: 'pusher',
    key: import.meta.env.VITE_PUSHER_APP_KEY,
    cluster: import.meta.env.VITE_PUSHER_APP_CLUSTER ?? 'mt1',
    wsHost: import.meta.env.VITE_PUSHER_HOST ? import.meta.env.VITE_PUSHER_HOST : `ws-${import.meta.env.VITE_PUSHER_APP_CLUSTER}.pusher.com`,
    wsPort: import.meta.env.VITE_PUSHER_PORT ?? 80,
    wssPort: import.meta.env.VITE_PUSHER_PORT ?? 443,
    forceTLS: (import.meta.env.VITE_PUSHER_SCHEME ?? 'https') === 'https',
    enabledTransports: ['ws', 'wss'],
});

This JavaScript setup allows your Laravel frontend app to communicate with the WebSocket server.

Step 7: Create a Broadcast Event

Now, let’s create a Laravel event that you want to broadcast using WebSockets. For this example, we’ll create a simple event called NewEvent. Create a new file in the app/Events directory called NewEvent.php. We can make the event with the following command:

php artisan make:event NewEvent

Update the NewEvent.php with the following codes:

namespace App\Events;

use Illuminate\Broadcasting\Channel;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;

// make sure to implement the ShouldBroadcast interface. 
// This is needed so that Laravel knows to broadcast the event over a WebSocket connection
class NewEvent implements ShouldBroadcast 
{
    use Dispatchable, InteractsWithSockets, SerializesModels;

    public $message;

    public function __construct($message)
    {
        $this->message = $message;
    }

    public function broadcastOn(): array
    {
        return [
            // we'll broadcast the event on a public channel called new-public-channel.
            new Channel('new-public-channel'),
        ];
    }
}

This event will be broadcasted to the specified channel.

Step 8: Broadcast the Event

In your Laravel routes (e.g., routes/web.php), create a route that dispatches the event:

use App\Events\NewEvent;

Route::get('/event', function () {
    NewEvent::dispatch(request()->msg);

    return 'Message sent!';
});

This route will dispatch the NewEvent event when accessed, simulating a real-time event trigger.

Step 9: Listen for the Event in JavaScript

In your JavaScript, you can now listen for the broadcasted event and handle it accordingly. For example:

// resources/js/bootstrap.js

window.Echo = new Echo({
    // ...
});

window.Echo.channel("new-public-channel").listen("NewEvent", (e) => {
  console.log(e);
});

This JavaScript code listens for the NewEvent broadcast on the new-public-channel and logs the event data.

Read also:

Step 10: Include the app.js in Our Laravel Frontend

To enable event reception, we need to include app.js, which imports bootstrap.js, in our Laravel frontend. For example, let’s include it in the welcome.blade.php file:

<html lang="">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">

        <title>Laravel</title>

        <!-- Fonts -->
        <link rel="preconnect" href="https://fonts.bunny.net">
        <link href="https://fonts.bunny.net/css?family=figtree:400,600&display=swap" rel="stylesheet" />

        <!-- Styles -->
        <style>
            <!-- long css -->
        </style>
        <!-- include app.js -->
        @vite(['resources/js/app.js'])
    </head>

Step 11: Test the WebSocket

To test your WebSocket implementation, follow these steps:

  1. Visit the home page that serves welcome.blade.php (e.g., http://127.0.0.1:8000) and open the Developer Tools and navigate to Console tab.
    home.png
  2. Open a new tab in your web browser.
  3. Visit the /event route in your Laravel application.
  4. Add an additional query parameter, for example, /event?msg=itworks, to send an event with a message. This action will dispatch the NewEvent event and trigger the JavaScript listener, allowing you to test and verify your WebSocket functionality.
    event-route.png
  5. Back to the home page tab and check the Dev Tools Console.
    home-receive-event.png

Congratulations! You’ve successfully set up the foundation for Laravel WebSockets using Soketi.

Conclusion

We’ve learned how to set up a WebSocket server, broadcast events, and make our app respond instantly to what users do. It’s like making your app come alive!

Real-time apps can do amazing things, like letting people chat instantly or work together smoothly. With Laravel and Soketi, you’ve got the tools to make these cool things happen. Happy coding!

The repository for this example can be found at fajarwz/blog-laravel-soketi.

Laravel News Links