Laravel – DebugEverything https://blog.debugeverything.com A new way to learn programming Wed, 15 Feb 2023 13:08:51 +0000 en-US hourly 1 https://wordpress.org/?v=7.1.4 https://blog.debugeverything.com/wp-content/uploads/2021/04/cropped-DE_white-32x32.png Laravel – DebugEverything https://blog.debugeverything.com 32 32 The Top 5 Essential Features of Laravel for Web Development https://blog.debugeverything.com/the-top-5-essential-features-of-laravel-for-web-development/ https://blog.debugeverything.com/the-top-5-essential-features-of-laravel-for-web-development/#respond Wed, 15 Feb 2023 13:07:37 +0000 https://blog.debugeverything.com/?p=2506 Laravel is a PHP framework that has gained immense popularity among web developers due to its easy-to-use syntax, expressive code structure, and powerful features. In this article, we will explore the top 7 essential features of Laravel with code examples.

Blade Templating Engine

Blade Templating Engine – Blade is a lightweight templating engine that allows developers to create reusable components and templates. It is easy to learn and provides a clean syntax for creating views and layouts. With Blade, developers can create dynamic templates that are easy to maintain and update. Here’s an example of a Blade template that displays a list of products:

<!-- products.blade.php -->
<ul>
    @foreach ($products as $product)
        <li>{{ $product->name }}</li>
    @endforeach
</ul>

Eloquent ORM

Eloquent is Laravel’s object-relational mapping (ORM) system that provides an intuitive way of working with databases. It allows developers to define database tables as PHP classes, and then interact with them using object-oriented syntax. Eloquent also provides features like database migrations, query builder, and relationships between tables. Here’s an example of defining a model in Laravel using Eloquent:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Product extends Model
{
    protected $fillable = ['name', 'description', 'price'];
}

Artisan Command-Line Interface

Artisan is a powerful command-line interface that comes with Laravel. It provides a set of tools for developers to automate common tasks, such as creating models, generating migrations, and running database seeders. With Artisan, developers can save time and focus on writing code rather than manually executing repetitive tasks. Here’s an example of generating a migration using Artisan:

$ php artisan make:migration create_products_table --create=products

Authentication and Authorization

Laravel provides a robust authentication system that includes features like password hashing, login throttling, and CSRF protection. It also has built-in support for authorization, which allows developers to define access levels for different parts of the application. With Laravel’s authentication and authorization system, developers can quickly add user registration and login functionality to their applications. Here’s an example of defining a route that requires authentication:

Route::get('/dashboard', function () {
    // Only authenticated users can access this route
})->middleware(['auth']);

Testing and Debugging

Laravel comes with built-in support for testing and debugging. It includes PHPUnit, a popular testing framework for PHP, and allows developers to write unit tests for their application’s code. Laravel also provides an extensive set of debugging tools, including error handling, logging, and a debugger that can be used to inspect and debug code. Here’s an example of writing a test in Laravel using PHPUnit:

class ProductTest extends TestCase
{
    public function testProductCreation()
    {
        $product = new Product(['name' => 'Laptop', 'description' => 'A high-performance laptop', 'price' => 1000]);
        $this->assertEquals('Laptop', $product->name);
    }
}

To summarise, Laravel is a robust PHP framework that includes many vital features that make web development simple and effective. Laravel is a fantastic alternative for constructing modern online applications, thanks to its Blade templating engine, Eloquent ORM, Artisan command-line interface, authentication and authorisation system, testing and debugging tools, queues, and routeing and controllers.

]]>
https://blog.debugeverything.com/the-top-5-essential-features-of-laravel-for-web-development/feed/ 0
Validation in Laravel: A Comprehensive Guide with Examples https://blog.debugeverything.com/validation-in-laravel-a-comprehensive-guide-with-examples/ https://blog.debugeverything.com/validation-in-laravel-a-comprehensive-guide-with-examples/#respond Wed, 25 Jan 2023 13:48:38 +0000 https://blog.debugeverything.com/?p=2483 Validation is an important component of any web application since it ensures that the data received from the user is correct and in the desired format. Laravel, a popular PHP web application framework, makes validation simple and straightforward. In this post, we’ll go over the various validation methods available in Laravel and show you how to use them.

Method 1: Using Form Request Validation

Laravel provides a built-in feature called Form Request Validation, which allows you to create a separate class for validation rules. The class is then used to validate the incoming request data before it is passed to the controller method. Here’s an example of how to use Form Request Validation:

class StoreBlogPost extends FormRequest
{
    public function authorize()
    {
        return true;
    }

    public function rules()
    {
        return [
            'title' => 'required|min:3|max:255',
            'body' => 'required|min:10',
        ];
    }
}

In the above example, we have created a class called StoreBlogPost that extends the FormRequest class. The authorize() method returns true, which means that the request is authorized, and the rules() method returns an array of validation rules for the title and body fields.

Method 2: Using Validation Helper Functions

Laravel provides several validation helper functions that can be used to validate incoming request data. Here’s an example of how to use the validate() helper function:

$validatedData = request()->validate([
    'title' => 'required|min:3|max:255',
    'body' => 'required|min:10',
]);

In the above example, we are using the validate() helper function to validate the incoming request data for the title and body fields. The function returns the validated data, which can then be used in the controller method.

Method 3: Using Custom Validation Rules

Laravel allows you to create custom validation rules, which can be reused across the application. Here’s an example of how to create a custom validation rule:

class UniqueSlugRule
{
    public function validate($attribute, $value, $parameters, $validator)
    {
        return !Blog::whereSlug($value)->exists();
    }
}

In the above example, we have created a custom validation rule called UniqueSlugRule that checks if the slug already exists in the blogs table.

Method 4: Using Rule Objects

Laravel provides a way to create validation rules as objects, which allows for more complex validation logic. Here’s an example of how to create a rule object:

use Illuminate\Validation\Rule;

$validatedData = request()->validate([
    'title' => ['required', Rule::unique('blogs')->ignore(Blog::find($id))],
    'body' => 'required|min:10',
]);

In the above example, we are using the Rule facade to create a rule object that checks if the title is unique in the blogs table, ignoring the current blog post.

Method 5: Using the Validator facade

Laravel also allows you to validate data using the Validator facade. This method allows for more flexibility and control over the validation process. Here’s an example of how to use the Validator facade:

use Validator;

$validator = Validator::make(request()->all(), [
    'title' => 'required|min:3|max:255',
    'body' => 'required|min:10',
]);

if ($validator->fails()) {
    return redirect()->back()->withErrors($validator)->withInput();
}

In the above example, we are using the make() method of the Validator facade to create a new validator instance. The first argument is the data to be validated, and the second argument is the validation rules. We then check if the validation fails by calling the fails() method, and if it does, we redirect the user back with the errors and input.

Conclusion

Any web application must do validation, and Laravel offers various techniques for doing so. The process is straightforward and uncomplicated, regardless of whether you use Form Request Validation, helper functions, personalized validation rules, rule objects, or the Validator facade. We hope that this post has given you a thorough overview of validation in Laravel and some practical examples to use it in your own projects.

]]>
https://blog.debugeverything.com/validation-in-laravel-a-comprehensive-guide-with-examples/feed/ 0
Understanding Routing, Controllers and Eloquent in Laravel. https://blog.debugeverything.com/understanding-routing-controllers-and-eloquent-in-laravel/ https://blog.debugeverything.com/understanding-routing-controllers-and-eloquent-in-laravel/#respond Fri, 20 Jan 2023 14:38:21 +0000 https://blog.debugeverything.com/?p=2467 Laravel is a popular PHP framework for building web applications. If you’re new to Laravel, it can be a bit overwhelming to try to understand all the different concepts and features of the framework. In this post, we’ll take a closer look at three of the most important concepts in Laravel: routing, controllers and Eloquent.

Routing

Routing is the process of mapping URLs to specific actions in your Laravel application. When a user visits a specific URL, Laravel will use the routing rules you’ve defined to determine which controller and method should handle the request.

For example, let’s say you have a controller called BlogController with a method called index. You can define a route that maps the URL /blog to this controller and method like this:

Route::get('/blog', [BlogController:class,'index']);

This tells Laravel that when a user visits the /blog URL, the index method of the BlogController should be executed.

You can also define routes with parameters, for example:

Route::get('/blog/{id}', [BlogController:class,'show']);

This tells Laravel that when a user visits the /blog/{id} URL, the show method of the BlogController should be executed and the id will be passed as a parameter to the method.

Routing is a crucial part of any Laravel application, and understanding how to define and use routes is essential for building functional web applications.

Controllers

Controllers are the middlemen between the user and the application. They handle HTTP requests and return HTTP responses.

When a user visits a specific URL, the corresponding controller method will be executed. This method can interact with models to retrieve data, perform calculations, or even redirect the user to another page.

For example, let’s say you have a controller called BlogController with a method called index. This method will retrieve all the blog post from the database and return them to the user.

class BlogController extends Controller
{
    public function index()
    {
        $posts = Post::all();
        return view('blog.index', compact('posts'));
    }
}

Controllers are where the majority of the application logic takes place, and understanding how to create and use controllers is essential for building functional web applications.

Eloquent

Eloquent is Laravel’s Object-Relational Mapping (ORM) tool. It allows you to interact with your database using an object-oriented syntax. This means that you can use PHP classes to represent database tables, and each instance of the class represents a single row in the table.

For example, let’s say you have a table called posts, you can create a Post model like this:

class Post extends Model
{
    //
}

Now you can retrieve all the posts from the database and return them to the user like this:

$posts = Post::all();

Eloquent also provides a lot of useful methods for performing common database operations such as creating, reading, updating and deleting records. Understanding how to use Eloquent is crucial for building a web application that can persist data.

For example, to create a new post, you can use the create method:

$post = Post::create([
    'title' => 'My First Post',
    'body' => 'This is my first post.'
]);

To update a post, you can use the update method:

$post = Post::find(1);
$post->update(['title' => 'My Updated Post','body' => 'This is my updated post.']);

And to delete a post, you can use the delete method:

$post = Post::find(1);
$post->delete();

Eloquent also supports relationships between models, which allow you to define how different models are related to each other. For example, you could define a hasMany relationship between Post and Comment, which means that each post has many comments.

In conclusion, understanding routing, controllers and Eloquent is a great first step in learning Laravel. These concepts form the foundation of any Laravel application, and mastering them will give you a solid understanding of how the framework works. Once you have a good grasp of these concepts, you can start diving deeper into the framework and using more advanced features.

]]>
https://blog.debugeverything.com/understanding-routing-controllers-and-eloquent-in-laravel/feed/ 0
Understanding Collections in Laravel 8 [With Examples] https://blog.debugeverything.com/understanding-collections-in-laravel-8-with-examples/ https://blog.debugeverything.com/understanding-collections-in-laravel-8-with-examples/#comments Tue, 07 Jun 2022 22:53:20 +0000 https://blog.debugeverything.com/?p=2440 If you use Laravel every day or have used it in the past, you may have already noticed how Collections are an important if not fundamental part of the framework.

Some sites and even the official documentation often call Collections: “Arrays with steroids” and in this article you will know why.

Why Collections?

An Array is a simple data structure that contains one or more elements in a single variable. Arrays in PHP however have one major problem, they are not Object Oriented.

Collections on the other hand is a powerful Object Oriented feature that expands the possibilities when working with arrays in Laravel. Besides, Collections allows us to write code more efficiently in an easier way.

How to create Collections

The helper method collect() returns a new instance of the Illuminate\Support\Collection class. Therefore, creating a collection is as simple as:

$collection = collect([1, 2, 3]);
$collection = collect(['product' => 'Table', 'price' => 200]);

Laravel Collections – where()

The where() method filters a Collection by a given key/value pair. This method can receive up to three parameters, the first being the key you want to search, the second is the operator (=, <>, >=) and the third parameter is the value you want to compare.

Let’s say we have an online shop, and the user wants to filter the products by price, using this method will simplify this by a lot.

In the example below, we are filtering all products with price equal to $100.

$collection = collect([
    ['product' => 'Table', 'price' => 200],
    ['product' => 'Chair', 'price' => 100],
    ['product' => 'Lamp', 'price' => 150],
    ['product' => 'Mattress', 'price' => 100],
]);
 
$filtered = $collection->where('price', 100);
 
$filtered->all();
 
/*
    [
        ['product' => 'Chair', 'price' => 100],
        ['product' => 'Mattress', 'price' => 100],
    ]
*/

Remember that the second parameter of the function is the operator but if the third parameter is omitted, the default operator is = so you can change the operator if you need to “greater or equal (>=) $ 100″ for example.

This two snippets below return exactly the same result:

$collection = collect([
    ['product' => 'Table', 'price' => 200],
    ['product' => 'Chair', 'price' => 100],
    ['product' => 'Lamp', 'price' => 150],
    ['product' => 'Mattress', 'price' => 100],
]);
 
$filtered = $collection->where('price', 100);
$filtered = $collection->where('price', '=', 100); 

Laravel Collections – pluck()

The pluck() method returns all values from a given key. Let me show you how extremely useful this can be.

Consider the same example above, now imagine you need an array containing just the name of all the products, how would you do it? Exactly, using pluck().

$collection = collect([
    ['product' => 'Table', 'price' => 200],
    ['product' => 'Chair', 'price' => 100],
    ['product' => 'Lamp', 'price' => 150],
    ['product' => 'Mattress', 'price' => 100],
]);
 
$filtered = $collection->pluck('product');
 
$filtered->all();
 
/*
        ['Table', 'Chair', 'Lamp', 'Mattress']
*/

With this method you can also set what the key of the value in the response is, as in the example above we only have two properties in each item in the array, the key would have to be price.

$collection = collect([
    ['product' => 'Table', 'price' => 200],
    ['product' => 'Chair', 'price' => 100],
    ['product' => 'Lamp', 'price' => 150],
    ['product' => 'Mattress', 'price' => 100],
]);

$filtered = $collection->pluck('product', 'price');

$filtered->all();

/*
   ["200" => "Table", "100" => "Mattress", "150" => "Lamp"]
*/

Another important fact about this method that I need to mention is that if you have an object with nested properties, you can use the “dot” notation to access these values. I explain what I mean with the example below:

$collection = collect([
    [
        'speakers' => [
            'first_day' => ['Rosa', 'Alberto'],
            'second_day' => ['Angela', 'Monica'],
        ],
    ],
]);

$filtered = $collection->pluck('speakers.first_day');

$filtered->all();

/*
   ['Rosa', 'Alberto']
*/

I don’t know about you, but I find this method extremely useful for many situations.

Laravel Collection – contains()

The contains() method determines if the collection contains a certain item. You can pass a function to the method, which will determine if there is an element in the collection that matches a certain condition. This is the most basic function of this method.

$collection = collect([1, 2, 3, 4, 5]);
 
$collection->contains(function ($value, $key) {
    return $value > 5;
});

// false

Once again, let’s use our product collection as an example. Let’s think about the situation where we need to check if we have a certain product in our shop, we could use this method, which will return true or false, if the product exists in the shop or not.

$collection = collect([
    ['product' => 'Table', 'price' => 200],
    ['product' => 'Chair', 'price' => 100],
    ['product' => 'Lamp', 'price' => 150],
    ['product' => 'Mattress', 'price' => 100],
]);

$filtered = $collection->contains('product', 'Chair');

// true

Laravel Collections – duplicates()

Another method that can be very useful is duplicates(). It retrieves and returns duplicate values from the collection. In this first example, a very simple situation, but you can already understand how the method works.

The collection below contains 5 elements, 2 of which have repetitions (a, b), the method then returns a new array where the key refers to the position of the repeated element in the original array.

$collection = collect(['a', 'b', 'a', 'c', 'b']);
 
$collection->duplicates();
 
// [2 => 'a', 4 => 'b']

For example, we have two letters ‘a’ in the collection, so the method returns us [2 => 'a', 4 => 'b'] indicating that we have a repeat of the letter ‘a’ at position 2 in the original collection and repeat of the letter ‘b’ at position 4.

Now with a realistic example. Let’s say we registered some users, but the unique email validation wasn’t working perfectly and because of that we now have duplicate emails in our system and we need to find those duplicates, with the duplicates() method this becomes a very simple task:

$users = collect([
    ['email' => 'rosa@example.com', 'profession' => 'Project manager'],
    ['email' => 'alberto@example.com', 'profession' => 'Developer'],
    ['email' => 'angela@example.com', 'profession' => 'Project analyst'],
    ['email' => 'alberto@example.com', 'profession' => 'Developer'],
    ['email' => 'monica@example.com', 'profession' => 'Graphic designer'],
    ['email' => 'alberto@example.com', 'profession' => 'Developer N2'],
]);

$users->duplicates('email');

// [3 => 'alberto@example.com', 5 => 'alberto@example.com']

Laravel Collection – firstWhere()

The firstWhere() method returns the first element of the collection with the key/value pair that matches a given value. We’ve already seen the where() method, and it looks like this method doesn’t do much more, but you’d need a loop, an if and maybe a break, just to be able to reproduce what this method does.

The example below, very similar to the where() method example, with one exception, instead of returning two values, it returns only one, the first occurrence of a product with a value equal to $100.

$collection = collect([
    ['product' => 'Table', 'price' => 200],
    ['product' => 'Chair', 'price' => 100],
    ['product' => 'Lamp', 'price' => 150],
    ['product' => 'Mattress', 'price' => 100],
]);

$filtered = $collection->firstWhere('price', '100');

$filtered->all();

// ['product' => 'Chair', 'price' => 100]

(Bonus) Laravel Collection – groupBy()

And our last method of the list, the groupBy(), usually is an operation done directly using SQL in the database, but not always the data that we want to manipulate comes directly from there, in this case we can use this method to solve a similar problem, let’s see how to use it:

$users = collect([
    ['name' => 'Rosa Silva', 'team' => 'Back-end'],
    ['name' => 'Alberto Junior', 'team' => 'Back-end'],
    ['name' => 'Angela Maria', 'team' => 'Front-end'],
    ['name' => 'Tomas Costa', 'team' => 'Back-end'],
    ['name' => 'Monica Silveira', 'team' => 'Front-end'],
    ['name' => 'Lucia Oliveira', 'team' => 'Front-end'],
]);

$groups = $users->groupBy('team');

//    {
//        {
//          "Back-end": [
//            { "name": "Rosa Silva", "team": "Back-end" },
//            { "name": "Alberto Junior", "team": "Back-end" },
//            { "name": "Tomas Costa", "team": "Back-end" 
//          ],
//          "Front-end": [
//            { "name": "Angela Maria", "team": "Front-end" },
//            { "name": "Monica Silveira", "team": "Front-end" },
//            { "name": "Lucia Oliveira", "team": "Front-end" }
//          ]
//        }
//    }

As a result of the groupBy() on this collection, now we have two arrays, each one containing 3 elements, which corresponds exactly to the developers that are part of the front-end team and the other array the developers from the back-end team, as you can see, this method definitely gives you a hand when organizing your arrays.

]]>
https://blog.debugeverything.com/understanding-collections-in-laravel-8-with-examples/feed/ 1
Laravel Request Lifecycle: the best starting point for learning Laravel https://blog.debugeverything.com/laravel-request-lifecycle/ https://blog.debugeverything.com/laravel-request-lifecycle/#comments Wed, 30 Jun 2021 10:42:56 +0000 https://blog.debugeverything.com/?p=2153 Laravel, as you may be aware, is a powerful framework, and the Laravel request lifecycle is the best place to start when you want to learn more about the framework itself. I’ll describe what occurs between an HTTP request to your application and the response. An in-depth examination of the request lifecycle will aid our understanding of the Laravel structure.

Autoloader, kernel, Service Providers, Dispatch Request, and Router are just a few of the terms used in the Laravel Request Lifecycle. Once you have a thorough understanding of all of the terms, you will be more confident and at ease with the framework, and you will be able to extend various features in any way you see fit.

Laravel Request Lifecycle Overview

The public/index.php file serves as the entry point for all requests to a Laravel application. This file serves as the start point for the remainder of your framework to be loaded.

Laravel Request Lifecycle Starting point

The file loads the composer-generated autoloader definition before retrieving the Laravel application instance from bootstrap/app.php.

Laravel’s initial action is to build an instance of the application/Service Container.

Http/Console Kernels

During the Laravel request lifecycle, the incoming request is sent to either the Http Kernel or the Console Kernel, depending on the kind of request.

Laravel Request Lifecycle Kernels

The Http kernel extends the Illuminate\Foundation\Http\Kernel class, which defines an array of bootstrappers that will be run before the request is executed.

These bootstrappers configures for you, right away:

  • Error handling
  • Logging
  • Detect the application environment
  • Perform tasks that will be run before the request is executed

The HTTP kernel (app\HttpKernel.php) also defines a list of HTTP middleware through which all requests must pass before being handled by the application.

This middleware handles reading and writing the HTTP session, identifying whether the app is in maintenance mode, validating the CSRF token, and many other tasks.

The method signature for the HTTP Kernel’s handle() method is quite simple: it receives a Request and returns a Response.

    /**
     * Handle an incoming HTTP request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function handle($request)
    {
        // It does other things here

        return $response;
    }

Consider the Kernel to be a large black box that contains your entire application. It will return HTTP Responses if you feed it HTTP Requests.

Services Providers

One of the most important Kernels bootstrapping actions during the Laravel request lifecycle is loading the Service Providers for the app.

Laravel Request Lifecycle Service Providers

All the services providers for the application are configured in the config\app.php configuration files provider’s array.

'providers' => [

        /*
         * Laravel Framework Service Providers...
         */
        Illuminate\Auth\AuthServiceProvider::class,
        Illuminate\Broadcasting\BroadcastServiceProvider::class,
        Illuminate\Bus\BusServiceProvider::class,
        Illuminate\Cache\CacheServiceProvider::class,
        ...
        App\Providers\RouteServiceProvider::class,
    ],

Laravel iterate through the list of providers and instantiate each of them. After instantiating the providers, the register() method will be called on all the providers. Then, once all of the providers have been registered, the boot() method will be called for each provider.

Provider has its own lifecycle, will look something like this:

Instantiate providers -> register providers -> boot providers

The Service providers in the Laravel request lifecycle are in charge of bootstrapping all of the framework’s key elements, such as:

  • Database
  • Queue
  • Validation
  • Routing Components

Essentially every major feature offered by Laravel is bootstrapped and configured by a service provider.

Service providers are the most important aspect of the Laravel request lifecycle bootstrap process because they bootstrap and configure so many features provided by the framework.

Routing

One of the most important bootstrapped Service Providers in your application is the App\Providers\RouteServiceProvider. This Service Provider loads the route files contained within your application’s routes directory.

Laravel Request Lifecycle Routing

Once the application has been bootstrapped and all Service Providers have been registered, the Request will be handed off to the router for dispatching. The route will dispatch the request to a route or controller, as well as run any route-specific middleware.

// Route dispatch
Route::get('/', function () {
    return view('welcome');
});
// Controller dispatch
Route::get('profile', [UserController::class, 'show'])->middleware('auth');

Middleware provide a convenient mechanism for filtering or examining HTTP Requests entering your application.

If the request passes through all of the matched route’s assigned middleware, the route or controller method will be executed and the response will be sent back through the route’s chain of middleware.

Response

And the final step in the Laravel Request Lifecycle, is returning a response. All routes and controllers should provide a response that should be sent back to the user’s browser. Laravel provides several different ways to return responses.

When a route or controller method returns a response, the response will flow back outward through the route’s middleware, allowing the application the opportunity to alter or examine the outgoing response.

Typically, you won’t just be returning simple strings or arrays from your route actions. Instead, you will be returning full Illuminate\Http\Response instances or views.

A Response instance is derived from the Symfony\Component\Http\Foundation\Response class, which provides a number of methods for constructing HTTP responses.

One of the advantages returning a full Response instance, is that you can alter the HTTP status code and headers of the response.

Finally, once the response has passed through the middleware, the HTTP kernel’s handle() method provides the response object, and the index.php file uses the returned response to call the send() method.  The send() method sends the response content to the user’s web browser.

We have completed our journey through the Laravel request lifecycle!

]]>
https://blog.debugeverything.com/laravel-request-lifecycle/feed/ 2