<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Jeffrey Kwade</title>
    <description>The latest articles on DEV Community by Jeffrey Kwade (@rebelnii).</description>
    <link>https://dev.to/rebelnii</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F1044226%2F3377546a-f7e2-4de0-bfbf-bfd6573eded2.JPG</url>
      <title>DEV Community: Jeffrey Kwade</title>
      <link>https://dev.to/rebelnii</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/rebelnii"/>
    <language>en</language>
    <item>
      <title>Building a RESTful API with Laravel: Best Practices and Implementation Tips.</title>
      <dc:creator>Jeffrey Kwade</dc:creator>
      <pubDate>Mon, 05 Jun 2023 12:25:33 +0000</pubDate>
      <link>https://dev.to/rebelnii/building-a-restful-api-with-laravel-best-practices-and-implementation-tips-1lok</link>
      <guid>https://dev.to/rebelnii/building-a-restful-api-with-laravel-best-practices-and-implementation-tips-1lok</guid>
      <description>&lt;p&gt;In today's interconnected world, building robust and efficient APIs has become a crucial aspect of web development. Laravel, one of the most popular PHP frameworks, provides developers with a powerful toolkit for creating RESTful APIs. With its elegant syntax, extensive features, and active community, Laravel simplifies the process of designing and implementing APIs, allowing developers to focus on delivering high-quality services.&lt;/p&gt;

&lt;p&gt;In this blog post, we will delve into the fascinating world of building RESTful APIs with Laravel. We will explore the best practices, implementation tips, and essential considerations for creating well-designed and scalable APIs. Whether you are a seasoned Laravel developer or just getting started with API development, this guide will equip you with the knowledge and techniques to build robust APIs with ease.&lt;/p&gt;

&lt;p&gt;Throughout this article, we will cover various aspects of API development using Laravel, including defining routes, handling requests and responses, implementing authentication and authorization mechanisms, validating input data, handling errors gracefully, and implementing pagination and versioning strategies. We will also explore some of Laravel's built-in features and packages specifically tailored for API development, such as Laravel Sanctum for API authentication and Laravel Passport for OAuth2 integration.&lt;/p&gt;

&lt;p&gt;By the end of this article, you will have a solid understanding of the best practices for building RESTful APIs with Laravel and be ready to embark on your own API development journey. So, let's dive in and discover how Laravel empowers developers to create efficient and reliable APIs that meet the needs of modern web applications.&lt;/p&gt;

&lt;p&gt;When constructing a RESTful API in Laravel, developers are confronted with a crucial decision: choosing between Laravel Sanctum and Laravel Passport.&lt;/p&gt;

&lt;p&gt;Let's look at both Laravel tools and decide which to choose.&lt;/p&gt;

&lt;p&gt;Laravel Sanctum is a powerful authentication package provided by the Laravel framework. It offers a lightweight and simple solution for implementing token-based authentication in your Laravel applications. With Sanctum, you can easily secure your API routes and control access to your resources.&lt;/p&gt;

&lt;p&gt;Sanctum uses API tokens for authentication, allowing clients to authenticate and access protected endpoints. It supports multiple authentication methods, including token-based authentication and session-based authentication. This flexibility makes it suitable for various types of applications, whether you're building a single-page application (SPA), a mobile app, or a traditional web application.&lt;/p&gt;

&lt;p&gt;One of the key features of Laravel Sanctum is its ability to generate long-lived and short-lived API tokens. Long-lived tokens are suitable for scenarios where you want persistent authentication, while short-lived tokens are ideal for temporary authentication, such as for mobile apps or SPA authentication.&lt;/p&gt;

&lt;p&gt;Sanctum also provides CSRF protection out of the box, securing your application against cross-site request forgery attacks. It integrates seamlessly with Laravel's existing authentication system, making it easy to authenticate users and authorize their access to different parts of your API.&lt;/p&gt;

&lt;p&gt;With Laravel Sanctum, you can focus on building your API endpoints and leave the authentication and security concerns to the package. It simplifies the process of implementing authentication in your Laravel applications, saving you time and effort.&lt;/p&gt;

&lt;p&gt;While Laravel Passport is a comprehensive OAuth2 server implementation provided by the Laravel framework. It allows developers to easily add API authentication to their Laravel applications, enabling secure communication between clients and servers.&lt;/p&gt;

&lt;p&gt;Passport provides a complete set of OAuth2 endpoints, allowing you to issue access tokens, refresh tokens, and revoke tokens. It follows the OAuth2 specification, which is widely used for authenticating and authorizing API requests.&lt;/p&gt;

&lt;p&gt;One of the key features of Laravel Passport is its simplicity and ease of use. It integrates seamlessly with Laravel's existing authentication system, making it straightforward to authenticate users and protect your API routes. With Passport, you can easily generate access tokens for your clients and use them to authenticate API requests.&lt;/p&gt;

&lt;p&gt;Passport supports various OAuth2 grant types, such as personal access tokens, password grant, authorization code grant, and implicit grant. This flexibility allows you to choose the most suitable authentication flow for your application, depending on the requirements and security considerations.&lt;/p&gt;

&lt;p&gt;Another advantage of Laravel Passport is its ability to generate API documentation automatically. Passport generates API documentation based on your API endpoints and authentication configuration, saving you time and effort in documenting your API for client developers.&lt;/p&gt;

&lt;p&gt;Additionally, Laravel Passport provides convenient features like token revocation and token scopes. Token revocation allows you to invalidate access tokens, while token scopes enable you to define fine-grained access permissions for your API resources.&lt;/p&gt;

&lt;p&gt;The big decision lies ahead now that we have explored both tools: Passport or Sanctum? Let's consult the official Laravel documentation for their recommendations.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Before getting started, you may wish to determine if your application would be better served by Laravel Passport or Laravel Sanctum. If your application absolutely needs to support OAuth2, then you should use Laravel Passport.&lt;/p&gt;

&lt;p&gt;However, if you are attempting to authenticate a single-page application, mobile application, or issue API tokens, you should use Laravel Sanctum. Laravel Sanctum does not support OAuth2; however, it provides a much simpler API authentication development experience.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Now, let's explore the following best practices and helpful tips.&lt;/p&gt;

&lt;h2&gt;
  
  
  Versioning
&lt;/h2&gt;

&lt;p&gt;Versioning is an essential aspect of building RESTful APIs in Laravel to ensure compatibility, maintainability, and smooth evolution of your API over time. Laravel provides several strategies for API versioning, each with its advantages and considerations. Let's explore some common versioning strategies used in Laravel RESTful APIs:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;URL Versioning: With URL-based versioning, you include the version number in the API endpoint URL. For example:&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

Route::middleware('auth:sanctum')-&amp;gt;prefix('v1')-&amp;gt;group(function(){

});


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;This approach allows you to have different versions of the API accessible via distinct URLs. It provides clear separation between versions and makes it easy to manage and maintain different API versions. However, it can result in longer URLs and may require additional routing configuration. &lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Folders Versioning: Versioning also allows developers to properly structure their Laravel folders like Controller, Resources, Request and Routes.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F7mpjtsxymmknb3qnufko.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F7mpjtsxymmknb3qnufko.png" alt="jeffrey kwade"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;From the image above, you can see that I have implemented versioning in my Laravel project by creating a separate folder named 'V1' within the 'Controllers' and 'Resources' directories. This naming convention helps me organize and distinguish the files belonging to the first version of my API.&lt;/p&gt;

&lt;p&gt;By adopting this structure, it becomes clear that all the files within the 'V1' folder are specific to the initial version of my API. This approach simplifies the management of different API versions, allowing me to make updates or introduce new features without affecting the existing functionality.&lt;/p&gt;

&lt;p&gt;With this versioning setup, I can easily navigate and maintain my codebase, ensuring that the changes made in subsequent versions do not conflict with the initial implementation. It also helps me adhere to the principles of backward compatibility, enabling clients to continue using the API without disruption while transitioning to newer versions at their own pace.&lt;/p&gt;

&lt;p&gt;By following this versioning strategy, I can effectively organize and evolve my Laravel API, making it easier to manage and provide a consistent experience for API consumers across different versions.&lt;/p&gt;

&lt;h2&gt;
  
  
  Data validation
&lt;/h2&gt;

&lt;p&gt;In Laravel, developers have two main approaches to validate incoming data: validating data directly within the controller or using a form request file.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Validating Data within the Controller: In this approach, data validation is performed directly within the controller method that handles the request. Developers define the validation rules and apply them to the incoming data using Laravel's validation system. Here's an example:&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight php"&gt;&lt;code&gt;

&lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;function&lt;/span&gt; &lt;span class="n"&gt;store&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;Request&lt;/span&gt; &lt;span class="nv"&gt;$request&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="nv"&gt;$validatedData&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nv"&gt;$request&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;validate&lt;/span&gt;&lt;span class="p"&gt;([&lt;/span&gt;
        &lt;span class="s1"&gt;'name'&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="s1"&gt;'required|max:255'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
        &lt;span class="s1"&gt;'email'&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="s1"&gt;'required|email|unique:users'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
        &lt;span class="s1"&gt;'password'&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="s1"&gt;'required|min:8'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="p"&gt;]);&lt;/span&gt;

    &lt;span class="c1"&gt;// Proceed with storing the data or performing further actions&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;In the above example, the &lt;code&gt;validate&lt;/code&gt; method is called on the &lt;code&gt;$request&lt;/code&gt; object, and the validation rules are defined as an array. If any of the validation rules fail, Laravel automatically redirects back to the form with the validation errors.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Using Form Request Files:
Laravel provides a convenient way to handle data validation by using form request files. Form requests are custom classes that extend Laravel's &lt;code&gt;Illuminate\Foundation\Http\FormRequest&lt;/code&gt; class. These classes encapsulate the validation rules for a specific request and provide a dedicated place to define and manage the validation logic. Here's an example:&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class StoreUserRequest extends FormRequest
{
    public function rules()
    {
        return [
            'name' =&amp;gt; 'required|max:255',
            'email' =&amp;gt; 'required|email|unique:users',
            'password' =&amp;gt; 'required|min:8',
        ];
    }
}


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;In the above example, the &lt;code&gt;rules&lt;/code&gt; method is overridden to define the validation rules. To use the form request, you simply type-hint it in your controller method:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

public function store(StoreUserRequest $request)
{
    // The request has already been validated at this point
    // Proceed with storing the data or performing further actions
}


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Always remember to set the &lt;code&gt;authorize&lt;/code&gt; function to true, this will allow the &lt;code&gt;rules&lt;/code&gt; function to take effect.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

class StoreCommentRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array&amp;lt;string, mixed&amp;gt;
     */
    public function rules()
    {
        return [
            //
        ];
    }
}


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;By returning &lt;code&gt;true&lt;/code&gt;, it indicates that any authenticated user is authorized to proceed with the requested action. This means that the authorization check is bypassed, and all users are considered authorized. This approach is suitable when you want to skip the authorization step and allow all authenticated users to perform the action.&lt;/p&gt;

&lt;p&gt;Both approaches serve the purpose of validating incoming data in Laravel. The choice between them depends on the complexity and reusability of the validation logic. Form request files provide a more structured and reusable way to handle validation, while validating within the controller can be more straightforward for simple cases.&lt;/p&gt;

&lt;h2&gt;
  
  
  Resources
&lt;/h2&gt;

&lt;p&gt;In Laravel, resources are a powerful feature that allows you to define a consistent and structured way to transform and format your API responses. Resources provide a convenient and flexible approach to transform your models and data into a well-defined JSON representation.&lt;/p&gt;

&lt;p&gt;To create a resource in Laravel, you can use the &lt;code&gt;make:resource&lt;/code&gt; Artisan command. For example, to generate a &lt;code&gt;UserResource&lt;/code&gt; that represents a user model, you can run the following command:&lt;/p&gt;

&lt;p&gt;&lt;code&gt;php artisan make:resource UserResource&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;This command will create a new &lt;code&gt;UserResource&lt;/code&gt; class in the &lt;code&gt;app/Http/Resources&lt;/code&gt; directory. Inside the resource class, you can define how the user model should be transformed and formatted when it's returned as a response.&lt;/p&gt;

&lt;p&gt;A basic resource class typically includes a &lt;code&gt;toArray&lt;/code&gt; method, where you specify the attributes and relationships you want to include in the transformed output. Here's an example of a &lt;code&gt;UserResource&lt;/code&gt;:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

&amp;lt;?php

namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\JsonResource;

class UserResource extends JsonResource
{
    public function toArray($request)
    {
        return [
            'id' =&amp;gt; $this-&amp;gt;id,
            'name' =&amp;gt; $this-&amp;gt;name,
            'email' =&amp;gt; $this-&amp;gt;email,
            'created_at' =&amp;gt; $this-&amp;gt;created_at,
            'updated_at' =&amp;gt; $this-&amp;gt;updated_at,
        ];
    }
}


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;In this example, the &lt;code&gt;UserResource&lt;/code&gt; includes the &lt;code&gt;id&lt;/code&gt;, &lt;code&gt;name&lt;/code&gt;, &lt;code&gt;email&lt;/code&gt;, &lt;code&gt;created_at&lt;/code&gt;, and &lt;code&gt;updated_at&lt;/code&gt; attributes of the user model.&lt;/p&gt;

&lt;p&gt;Once you have defined a resource, you can use it in your API controllers to transform your model instances before returning them as responses. Here's an example of how you can use the &lt;code&gt;UserResource&lt;/code&gt;:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

use App\Http\Resources\UserResource;
use App\Models\User;
use Illuminate\Http\Request;

class UserController extends Controller
{
    public function show(Request $request, $id)
    {
        $user = User::findOrFail($id);

        return new UserResource($user);
    }
}


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;When return multiple users simply call the &lt;code&gt;UserResource&lt;/code&gt; with a collection. here's an example:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

use App\Http\Resources\UserResource;
use App\Models\User;
use Illuminate\Http\Request;

class UserController extends Controller
{
    public function index()
    {
        $user = User::all();

        return UserResource::collection($user);
    }
}


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;In this example, when the show method is called, it retrieves a user model by its ID and returns a transformed response using the &lt;code&gt;UserResource&lt;/code&gt;. The user model will be automatically transformed based on the &lt;code&gt;toArray&lt;/code&gt; method defined in the resource.&lt;/p&gt;

&lt;p&gt;Resources provide a convenient way to customize the structure and formatting of your API responses. They can handle relationships, include additional data, and apply conditional formatting based on your specific requirements. Resources help to keep your API responses consistent and maintainable, especially when dealing with complex data structures and relationships.&lt;/p&gt;

&lt;h2&gt;
  
  
  Disabling data wrapping
&lt;/h2&gt;

&lt;p&gt;By default, a resource is automatically wrapped in a data key once the JSON serialization is done.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

{
    "data": [
        {
            "id": 1,
            "name": "John Doe",
            "email": "john@doe.com"
        },
        {
            "id": 2,
            "name": "Jane Doe",
            "email": "jane@doe.com"
        }
    ]
}


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;This wrapping is useful for including additional keys, like &lt;code&gt;links&lt;/code&gt; and &lt;code&gt;meta&lt;/code&gt;, when using pagination. However, it may only be necessary for some projects.&lt;/p&gt;

&lt;p&gt;To disable it, add &lt;code&gt;JsonResource::withoutWrapping()&lt;/code&gt; into the &lt;code&gt;boot&lt;/code&gt; function of your &lt;code&gt;AppServiceProvider&lt;/code&gt; of your Laravel application.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

/**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        JsonResource::withoutWrapping();
    }


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;h2&gt;
  
  
  Pagination
&lt;/h2&gt;

&lt;p&gt;Pagination in Laravel API allows you to divide large result sets into smaller, more manageable chunks called "pages." This helps improve performance by reducing the amount of data transferred over the network and provides a better user experience when dealing with large collections of data.&lt;/p&gt;

&lt;p&gt;Laravel provides built-in pagination support that you can easily incorporate into your API endpoints. Here's how you can use pagination in your Laravel API:&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

public function index(){
        return PostResource::collection(Post::query()-&amp;gt;paginate(3));
    }


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;And you'll get this as a response:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

{
    "data": [
        {
            "id": 21,
            "name": "John Doe",
            "email": "john@doe.com"
        },
        {
            "id": 22,
            "name": "Jane Doe",
            "email": "jane@doe.com"
        },
        // ...
    ],
    "links": {
        "first": "http://example.com/pagination?page=1",
        "last": "http://example.com/pagination?page=8",
        "prev": "http://example.com/pagination?page=2",
        "next": "http://example.com/pagination?page=4"
    },
    "meta": {
        "current_page": 3,
        "from": 21,
        "last_page": 8,
        "path": "http://example.com/pagination",
        "per_page": 10,
        "to": 30,
        "total": 86
    }
}


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;h2&gt;
  
  
  Conditional Attributes
&lt;/h2&gt;

&lt;p&gt;Conditional attributes in Laravel API resources allow you to include or exclude certain attributes based on specific conditions. This can be useful when you want to customize the response data based on different scenarios or user roles.&lt;/p&gt;

&lt;p&gt;To implement conditional attributes in Laravel API resources, you can make use of the &lt;code&gt;when()&lt;/code&gt; method provided by Laravel's API resource class. The &lt;code&gt;when()&lt;/code&gt; method accepts a condition and a callback, and the callback will be executed only if the condition evaluates to true. Within the callback, you can define the attributes that should be included based on the condition.&lt;/p&gt;

&lt;p&gt;Here's an example of how you can use conditional attributes in a Laravel API resource:&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

&amp;lt;?php

namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\JsonResource;

class UserResource extends JsonResource
{
    public function toArray($request)
    {
        return [
            'id' =&amp;gt; $this-&amp;gt;id,
            'name' =&amp;gt; $this-&amp;gt;name,
            'email' =&amp;gt; $this-&amp;gt;when(auth()-&amp;gt;user()-&amp;gt;isAdmin(), $this-&amp;gt;email),
            'phone' =&amp;gt; $this-&amp;gt;when(auth()-&amp;gt;user()-&amp;gt;isPremium(), $this-&amp;gt;phone),
        ];
    }
}


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;In the example above, the &lt;code&gt;UserResource&lt;/code&gt; class includes conditional attributes based on the user's role.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;The &lt;code&gt;email&lt;/code&gt; attribute will only be included if the authenticated user is an admin.&lt;/li&gt;
&lt;li&gt;The &lt;code&gt;phone&lt;/code&gt; attribute will only be included if the authenticated user is a premium user.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;In conclusion, building RESTful APIs with Laravel not only empowers developers to create efficient and reliable APIs but also enhances the overall web development process by providing robust tools, best practices, and a supportive community, making it an excellent choice for API development in the modern web landscape. If you found this article helpful and want to stay updated with more insightful content, be sure to follow me on &lt;a href="https://github.com/kwadejeffrey" rel="noopener noreferrer"&gt;Github&lt;/a&gt;, &lt;a href="https://www.linkedin.com/in/jeffrey-kwade-7395b8237/" rel="noopener noreferrer"&gt;LinkedIN&lt;/a&gt;, &lt;a href="https://twitter.com/kwade_jeffrey" rel="noopener noreferrer"&gt;Twitter&lt;/a&gt; for regular updates, tips, and discussions. Let's connect and continue the conversation!&lt;/p&gt;

</description>
      <category>laravel</category>
      <category>tutorial</category>
      <category>php</category>
      <category>webdev</category>
    </item>
    <item>
      <title>The Battle of With vs Load in Eloquent: Which One Wins?</title>
      <dc:creator>Jeffrey Kwade</dc:creator>
      <pubDate>Tue, 02 May 2023 14:14:56 +0000</pubDate>
      <link>https://dev.to/rebelnii/the-battle-of-with-vs-load-in-eloquent-which-one-wins-4883</link>
      <guid>https://dev.to/rebelnii/the-battle-of-with-vs-load-in-eloquent-which-one-wins-4883</guid>
      <description>&lt;p&gt;In the realm of Laravel's Eloquent ORM, developers often find themselves faced with a crucial decision: should they employ the "with" method or the "load" method? These two methods, although similar in purpose, have subtle differences that can significantly impact the performance and behavior of database queries. It's a battle that has intrigued developers for years, as they strive to find the optimal approach for fetching related data in their applications. In this article, we delve deep into the battle of "With vs Load" in Eloquent, aiming to uncover the strengths, weaknesses, and best use cases for each method. So, fasten your seatbelts as we embark on this journey to determine which one emerges as the ultimate winner in the quest for efficient and elegant data retrieval in Laravel.&lt;/p&gt;

&lt;h2&gt;
  
  
  Understanding Eloquent relationships?
&lt;/h2&gt;

&lt;p&gt;Eloquent relationships are a fundamental feature of the Laravel framework's Eloquent ORM (Object-Relational Mapping) system. These relationships define the associations between different database tables/entities and enable you to work with related data seamlessly. With Eloquent relationships, you can effortlessly retrieve, manipulate, and perform common database operations on associated records.&lt;/p&gt;

&lt;p&gt;By establishing relationships between your database tables, you can create powerful connections that mirror real-world associations, such as one-to-one, one-to-many, and many-to-many relationships. Eloquent provides a fluent and expressive syntax to define and work with these relationships, making it easier to navigate and manipulate your application's data.&lt;/p&gt;

&lt;p&gt;Whether you need to fetch a user's posts, retrieve all comments on a blog article, or retrieve a product's categories, Eloquent relationships provide a clean and intuitive way to query and work with related data.&lt;/p&gt;

&lt;h2&gt;
  
  
  Exploring &lt;code&gt;With()&lt;/code&gt; eloquent method.
&lt;/h2&gt;

&lt;p&gt;The &lt;code&gt;with()&lt;/code&gt; method in Laravel is used to eager load relationships when querying a model. By eager loading relationships, you can retrieve the related models along with the main model in a more efficient way, reducing the number of database queries.&lt;/p&gt;

&lt;p&gt;"Eager" refers to the concept of associating related models in a single query instead of using multiple queries. When using eager loading, you fetch the main set of data and also preload the related models associated with that data in a single database query, rather than executing additional queries for each related model.&lt;/p&gt;

&lt;p&gt;This approach is beneficial in situations where you have a collection of items and need to access the related models for each item. By eager loading the related models, you can optimize performance by reducing the number of queries required to fetch the associated data.&lt;/p&gt;

&lt;p&gt;Without eager loading, you would need to execute a separate query for each item in the initial set to retrieve its related models. This can lead to the "N+1" problem, where the number of queries becomes proportional to the number of items in the set.&lt;/p&gt;

&lt;p&gt;Here are some key points to understand about the &lt;code&gt;with()&lt;/code&gt; method:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;The &lt;code&gt;with()&lt;/code&gt; method is called on the query builder instance, typically when retrieving models from the database.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;When you use the &lt;code&gt;with()&lt;/code&gt; method, Laravel will automatically fetch the related models and include them in the query result.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;It uses separate queries to load the related models, based on the relationships defined in your models.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;The related models are then associated with the main model using their defined relationships.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Unveiling the &lt;code&gt;load()&lt;/code&gt; Method.
&lt;/h2&gt;

&lt;p&gt;The &lt;code&gt;load()&lt;/code&gt; method in Laravel is used to load relationships on a model that has already been retrieved from the database. It allows you to load specific relationships dynamically after the initial retrieval.&lt;/p&gt;

&lt;p&gt;Here are some key points to understand about the &lt;code&gt;load()&lt;/code&gt; method:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;The &lt;code&gt;load()&lt;/code&gt; method is called on an instance of a model.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;When you use the &lt;code&gt;load()&lt;/code&gt; method, Laravel will fetch the related models and associate them with the main model.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;It uses separate queries to load the related models, similar to eager loading with &lt;code&gt;with()&lt;/code&gt;, but it applies to an already retrieved model.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;The &lt;code&gt;load()&lt;/code&gt; method allows you to load relationships on-demand, based on your specific needs.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;It gives you flexibility in choosing which relationships to load, depending on the context of your application.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  The Battle of &lt;code&gt;with()&lt;/code&gt; vs &lt;code&gt;load()&lt;/code&gt;:
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;Applying Conditions: Both &lt;code&gt;with()&lt;/code&gt; and &lt;code&gt;load()&lt;/code&gt; methods in Eloquent allow you to apply conditions to the eager loading of relationships.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;With &lt;code&gt;with()&lt;/code&gt;, you can apply conditions by passing an array of key-value pairs, where the key represents the relationship name and the value represents the conditions to be applied. &lt;/p&gt;

&lt;p&gt;For example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;$users = User::with(['posts' =&amp;gt; function ($query) {
    $query-&amp;gt;where('published', true);
}])-&amp;gt;get();

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the example above, the &lt;code&gt;with()&lt;/code&gt; method is used to eager load the posts relationship for the User model, but only load the posts that are published.&lt;/p&gt;

&lt;p&gt;Similarly, with &lt;code&gt;load()&lt;/code&gt;, you can also apply conditions by chaining the where method on the relationship. &lt;/p&gt;

&lt;p&gt;For example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;$user = User::find(1);
$user-&amp;gt;load(['posts' =&amp;gt; function ($query) {
    $query-&amp;gt;where('published', true);
}]);

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this example, the &lt;code&gt;load()&lt;/code&gt; method is used to load the posts relationship for a specific user, but only load the published posts.&lt;/p&gt;

&lt;p&gt;Both with() and load() methods provide flexibility to apply conditions when eager loading relationships in Laravel's Eloquent ORM.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Usage Context: The &lt;code&gt;with()&lt;/code&gt; method in Laravel is used on the query builder instance, typically when retrieving models from the database. When you use the &lt;code&gt;with()&lt;/code&gt; method, Laravel automatically fetches the related models and includes them in the query result.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;On the other hand, the &lt;code&gt;load()&lt;/code&gt; method is called on an "instance" of a model. With the &lt;code&gt;load()&lt;/code&gt; method, you can fetch the related models and associate them with the main model. Unlike eager loading, the &lt;code&gt;load()&lt;/code&gt; method allows you to load relationships on-demand, based on your specific needs. It provides flexibility in choosing which relationships to load, depending on the context of your application.&lt;/p&gt;

&lt;p&gt;A key difference between &lt;code&gt;with()&lt;/code&gt; and &lt;code&gt;load()&lt;/code&gt; lies in how and when the related models are fetched. With &lt;code&gt;with()&lt;/code&gt;, the related models are fetched in the initial query, while with &lt;code&gt;load()&lt;/code&gt;, the related models are fetched separately as needed.&lt;/p&gt;

&lt;p&gt;Using the &lt;code&gt;load()&lt;/code&gt; method can be advantageous when you want to control the loading of relationships dynamically, based on runtime conditions or specific user actions. It allows you to minimize unnecessary queries and optimize performance by loading only the relationships that are necessary in a given context.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Multiple Relationships: &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;code&gt;with()&lt;/code&gt;: With &lt;code&gt;with()&lt;/code&gt;, you can eager load multiple relationships using an array or a comma-separated list of relationship names. This allows you to specify and load multiple relationships efficiently in a single query.&lt;br&gt;
Example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;$users = User::with(['posts', 'comments'])-&amp;gt;get();
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;load()&lt;/code&gt;:With load(), you can load multiple relationships individually by calling the &lt;code&gt;load()&lt;/code&gt; method multiple times on the model instance. This allows you to load specific relationships on a per-instance basis as needed.&lt;br&gt;
Example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;$user = User::find(1);
$user-&amp;gt;load('posts');
$user-&amp;gt;load('comments');
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;Eager Loading:&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;code&gt;with()&lt;/code&gt;: The &lt;code&gt;with()&lt;/code&gt; method performs eager loading of relationships, which means it retrieves the related data along with the main query in a single database call. This helps reduce the number of database queries and enhances performance, especially when dealing with large datasets or complex relationships.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;load()&lt;/code&gt;: The &lt;code&gt;load()&lt;/code&gt; method performs lazy loading of relationships, which means it retrieves the related data on-demand when accessed for the first time. This approach may result in additional database queries if multiple relationships are loaded separately.&lt;/p&gt;

&lt;h2&gt;
  
  
  Winner
&lt;/h2&gt;

&lt;p&gt;In conclusion, the battle of "With vs Load" in Laravel's Eloquent ORM ultimately declares you, the developer building the application, as the ultimate winner. The &lt;code&gt;with()&lt;/code&gt; method shines when you need to eagerly load relationships during the initial retrieval of models, optimizing performance by reducing queries and eliminating the "N+1" problem. On the other hand, the &lt;code&gt;load()&lt;/code&gt; method empowers you with the flexibility to load relationships on-demand, allowing you to dynamically fetch related models based on specific runtime conditions or user actions.&lt;/p&gt;

&lt;p&gt;The choice between &lt;code&gt;with()&lt;/code&gt; and &lt;code&gt;load()&lt;/code&gt; depends entirely on your application's unique requirements and usage context. If you already know in advance which relationships you need to fetch, &lt;code&gt;with()&lt;/code&gt; becomes an excellent choice for optimizing database queries. However, if you seek greater control over relationship loading based on specific scenarios, the &lt;code&gt;load()&lt;/code&gt; method proves invaluable, allowing you to fetch related models precisely when needed.&lt;/p&gt;

&lt;p&gt;As you harness the power of Laravel's Eloquent ORM, understanding the distinctions and strengths of each method empowers you to make informed decisions, leading to efficient and elegant data retrieval in your Laravel applications. So, embrace your role as the winner and leverage the capabilities of &lt;code&gt;with()&lt;/code&gt; and &lt;code&gt;load()&lt;/code&gt; to create exceptional applications that deliver optimal performance and meet your specific needs.&lt;/p&gt;

</description>
      <category>php</category>
      <category>database</category>
      <category>laravel</category>
      <category>webdev</category>
    </item>
    <item>
      <title>Database Optimization Techniques for Laravel Applications.</title>
      <dc:creator>Jeffrey Kwade</dc:creator>
      <pubDate>Wed, 12 Apr 2023 14:12:23 +0000</pubDate>
      <link>https://dev.to/rebelnii/database-optimization-techniques-for-laravel-applications-4n0h</link>
      <guid>https://dev.to/rebelnii/database-optimization-techniques-for-laravel-applications-4n0h</guid>
      <description>&lt;h2&gt;
  
  
  Optimizing database performance is an essential aspect of building robust web applications.
&lt;/h2&gt;

&lt;p&gt;There are several ways to optimize a database, some of which include Indexing, Proper schema design, Data normalization, Query optimization, Partitioning, Compression, and Proper hardware selection. In this blog post, I will focus on database caching.&lt;/p&gt;

&lt;p&gt;In this article, we'll explore how to optimize the performance of your database-driven Laravel application using caching. Caching is a powerful technique that can significantly reduce the number of queries needed to retrieve data, resulting in faster response times and improved user experience.&lt;/p&gt;

&lt;p&gt;Laravel offers several caching mechanisms, including file caching, database caching, and Redis caching. Each mechanism has its own strengths and weaknesses, and the choice of which to use will depend on your application's specific needs and requirements.&lt;/p&gt;

&lt;p&gt;To implement caching in your Laravel application, you can use the built-in caching functions and cache drivers provided by Laravel. You can also use third-party packages and libraries for more advanced caching functionality.&lt;/p&gt;

&lt;p&gt;However, caching also has its potential drawbacks, such as increased memory usage and the need for cache invalidation. To mitigate these issues, it is important to use a consistent naming convention for cache keys and to group related data using cache tags.&lt;/p&gt;

&lt;p&gt;To measure the effectiveness of caching in your application, you can use benchmarking and profiling tools to analyze your application's performance before and after implementing caching.&lt;/p&gt;

&lt;p&gt;By following these best practices for implementing caching in your Laravel application, you can improve its overall performance and provide a better user experience for your users.&lt;/p&gt;

&lt;p&gt;By default, Laravel is configured to use the file cache driver, which stores the serialized, cached objects on the server's filesystem. For larger applications, it is recommended that you use a more robust driver such as Memcached or Redis. You may even configure multiple cache configurations for the same driver. I'm going to be using the default cache driver in this article.&lt;/p&gt;

&lt;p&gt;In this example, we have a restaurant application that allows users to place orders and make table reservations. The application heavily relies on database transactions, which can result in slow performance and reduced user experience if not optimized. One effective way to optimize the performance of the application is by implementing database caching.&lt;/p&gt;

&lt;p&gt;Caching can help reduce the number of database queries needed to retrieve data and improve application responsiveness. In our restaurant application, we can cache the cart items that users add to their orders and reservations. By caching the cart items, we can reduce the number of queries needed to retrieve the items from the database and improve application performance.&lt;/p&gt;

&lt;p&gt;To implement caching in our restaurant application, we can leverage Laravel's caching mechanism. We can use Laravel's built-in caching functions and cache drivers to store the cart items in a cache store. We can also use Laravel's observer to delete cached data when the state of the cart items changes. For example, when a user adds new items to their cart or performs CRUD operations on the cart model, the observer can automatically invalidate the cache store and ensure that the latest data is retrieved from the database.&lt;/p&gt;

&lt;p&gt;Additionally, we can use cache tags to group related data and improve cache invalidation. By assigning tags to our cached data, we can easily invalidate related data when necessary and avoid clearing the entire cache store.&lt;/p&gt;

&lt;p&gt;To measure the effectiveness of our caching strategy in the restaurant application, we can use benchmarking and profiling tools like Clockwork. Clockwork is a free and open-source tool that can help us analyze the performance of our application before and after implementing caching.&lt;/p&gt;

&lt;p&gt;We can use Clockwork to track the number of database queries executed, the time taken to execute each query, and the memory used by the application. This information can help us identify any performance bottlenecks and optimize our caching strategy for maximum performance. &lt;br&gt;
To get started, we need to install Clockwork in our Laravel project via Composer. You can do this by running the following command in your terminal:&lt;/p&gt;

&lt;p&gt;&lt;code&gt;composer require --dev itsgoingd/clockwork&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;Now download the browser extension of Clockwork. Let's dive in!&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class CartController extends Controller
{
    //
    public function index(){
        return view('frontend.cart', [
            'carts' =&amp;gt; Cache::remember('cart', 60, function () {
                return Cart::where('user_id', auth()-&amp;gt;user()-&amp;gt;id())-&amp;gt;get();
            })
        ]);
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Let me explain the code above, this code block is a method in a Laravel controller that is used to display a user's shopping cart on the frontend of a web application. The &lt;code&gt;index()&lt;/code&gt; method retrieves the cart items from the database using the &lt;code&gt;Cart&lt;/code&gt; model and then stores the retrieved data in the cache for 60 seconds using the &lt;code&gt;Cache::remember()&lt;/code&gt; method.&lt;/p&gt;

&lt;p&gt;The &lt;code&gt;Cache::remember()&lt;/code&gt; method takes three parameters: the key for the cached data, the time-to-live (TTL) in minutes, and a closure that retrieves the data to be cached. In this case, the key is 'cart', the TTL is 60 minutes, and the closure returns the cart items from the database using the &lt;code&gt;Cart::where()&lt;/code&gt; query builder method.&lt;/p&gt;

&lt;p&gt;Once the cart items have been retrieved and cached, they are passed to the frontend.cart view using the &lt;code&gt;view()&lt;/code&gt; helper function. The cached cart items are then accessed in the view using the &lt;code&gt;$carts&lt;/code&gt; variable, which contains the cached data.&lt;/p&gt;

&lt;p&gt;Now let's create an observer for the cart model by using &lt;code&gt;php artisan make:observer CartObserver --model=Cart&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Laravel will then generate a new PHP file with method resource and we'll use this observer to clear our cached data whenever our Cart model changes state.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;?php

namespace App\Observers;

use App\Models\Cart;
use Illuminate\Support\Facades\Cache;

class CartObserver
{
    /**
     * Handle the Cart "created" event.
     *
     * @param  \App\Models\Cart  $cart
     * @return void
     */
    public function created(Cart $cart)
    {
        //
        Cache::forget('cart');
    }

    /**
     * Handle the Cart "updated" event.
     *
     * @param  \App\Models\Cart  $cart
     * @return void
     */
    public function updated(Cart $cart)
    {
        //
        Cache::forget('cart');
    }

    /**
     * Handle the Cart "deleted" event.
     *
     * @param  \App\Models\Cart  $cart
     * @return void
     */
    public function deleted(Cart $cart)
    {
        //
        Cache::forget('cart');
    }

    /**
     * Handle the Cart "restored" event.
     *
     * @param  \App\Models\Cart  $cart
     * @return void
     */
    public function restored(Cart $cart)
    {
        //
    }

    /**
     * Handle the Cart "force deleted" event.
     *
     * @param  \App\Models\Cart  $cart
     * @return void
     */
    public function forceDeleted(Cart $cart)
    {
        //
        Cache::forget('cart');
    }
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now, let's use Clockwork to compare the performance before and after implementing caching. This will help us determine the impact of caching on our application's performance.&lt;/p&gt;

&lt;p&gt;Before caching:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fkuizlmhye2bunvk7b858.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fkuizlmhye2bunvk7b858.png" alt="Before caching"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;After caching:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Felvh4jiija97me5dsxwy.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Felvh4jiija97me5dsxwy.png" alt="After caching"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Before implementing caching, our application made nine database queries in seventeen milliseconds. After implementing caching, we observed a significant improvement in performance, as our application made only eight queries in just eight milliseconds. The difference here is not only in the time recorded but also in the number of queries made.&lt;/p&gt;

&lt;p&gt;By caching frequently accessed data like cart items, we were able to reduce the number of queries needed to retrieve data from the database. This resulted in faster response times and improved overall performance. Imagine the impact of implementing caching on other frequently accessed data in our application - it can be mind-blowing!&lt;/p&gt;

&lt;p&gt;Caching is a powerful technique that can significantly improve the performance of database-driven applications. By reducing the number of database queries needed to retrieve data, caching can improve application responsiveness and user experience. It is important to choose the right caching strategy based on your application's specific needs and requirements to achieve the best results.&lt;/p&gt;

&lt;p&gt;Thanks for reading! I hope this article has been helpful in understanding the benefits of database caching and how to implement it in Laravel. If you have any questions or feedback, feel free to reach out to me on &lt;a href="https://twitter.com/kwade_jeffrey" rel="noopener noreferrer"&gt;twitter&lt;/a&gt; or &lt;a href="https://github.com/RebelNii" rel="noopener noreferrer"&gt;Github&lt;/a&gt;. Don't forget to follow me for more articles and updates.&lt;/p&gt;

</description>
      <category>laravel</category>
      <category>webdev</category>
      <category>database</category>
      <category>tutorial</category>
    </item>
    <item>
      <title>Testing Applications In Laravel.</title>
      <dc:creator>Jeffrey Kwade</dc:creator>
      <pubDate>Sun, 09 Apr 2023 00:29:23 +0000</pubDate>
      <link>https://dev.to/rebelnii/testing-applications-in-laravel-1899</link>
      <guid>https://dev.to/rebelnii/testing-applications-in-laravel-1899</guid>
      <description>&lt;p&gt;&lt;a href="https://dev.tourl"&gt;&lt;/a&gt;## Exploring Uncommon Error Messages When Running Tests in Laravel&lt;/p&gt;

&lt;p&gt;Hello developers,&lt;/p&gt;

&lt;p&gt;Welcome to my first episode in the "Testing Applications in Laravel" series. In this series, I will discuss different topics related to testing Laravel applications. Today, I will be discussing some rare errors that you might encounter while running tests in Laravel.&lt;/p&gt;

&lt;p&gt;When it comes to testing, encountering errors is inevitable. It can be frustrating, and it's common to feel like screaming at your computer. However, with a little knowledge and understanding, you can quickly fix these errors and make your tests pass.&lt;/p&gt;

&lt;p&gt;Today we shall discuss &lt;code&gt;Error: Test code or tested code did not (only) close its own output buffers&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;The error message Error: Test code or tested code did not (only) close its own output buffers is a common issue in PHPUnit tests when output buffering is used. Output buffering is a feature in PHP that allows you to capture the output of a script and manipulate it before it is sent to the browser.&lt;/p&gt;

&lt;p&gt;When PHPUnit tests are run, they capture any output from the test code and compare it with the expected output. If there is any output left in the buffer after the test is complete, it can cause this error.&lt;/p&gt;

&lt;p&gt;A junior developer reached out to me seeking assistance with the 'Error: Test code or tested code did not (only) close its own output buffers' issue. She had tried several methods, but none seemed to work. It brought back memories from when I first encountered this error, and I remember how frustrating it was to solve. Unfortunately, most articles related to this error are outdated or not clearly explained, which can make it challenging for junior developers to understand and resolve the issue.&lt;/p&gt;

&lt;p&gt;The issue with this error is that it can be difficult to diagnose because it doesn't always output a clear error message. In many cases, the console will generate a more specific error message that can help us pinpoint the root cause of the issue. This is why it's important to pay close attention to any error messages that are generated by your application and use them as a starting point for troubleshooting.&lt;/p&gt;

&lt;p&gt;So, to solve this error, we need to retrieve the output buffer levels using &lt;code&gt;ob_get_level()&lt;/code&gt;. This allows us to check whether there are any open output buffers that haven't been closed. We then retrieve the contents of the output buffer using &lt;code&gt;ob_get_contents()&lt;/code&gt; and clear the buffer using &lt;code&gt;ob_end_clean()&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;It's important to note that many solutions online advise using &lt;code&gt;ob_start()&lt;/code&gt; at the beginning of the test and &lt;code&gt;ob_end_clean()&lt;/code&gt; at the end. However, this doesn't always work for complex test cases.&lt;/p&gt;

&lt;p&gt;Now, let's move on to the coding part and see how we can implement this solution.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;?php

namespace Tests\Unit\V1\Admin\Vehicle;

use App\Http\Livewire\Admin\Vehicle\Add;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Foundation\Testing\WithoutMiddleware;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Storage;
use Livewire\Livewire;
use Tests\TestCase;

class VehicleTest extends TestCase
{
    use RefreshDatabase, WithoutMiddleware;



    public function test_create_new_vehicle_entry_with_file_upload()
    {

        ob_start();
        Storage::fake('avatars');

        $user = User::factory()-&amp;gt;create();
        $this-&amp;gt;actingAs($user);
        Auth::login($user);

        $file = UploadedFile::fake()-&amp;gt;image('avatar.jpg');

        Livewire::test(Add::class)
                -&amp;gt;set([
                    'name' =&amp;gt; 'Toyota',
                    'reg_num' =&amp;gt; 'GD-123-12',
                    'vin_num' =&amp;gt; 'kajsy',
                    'status' =&amp;gt; true,
                    'home_away' =&amp;gt; true,
                    'image' =&amp;gt; $file,
                    'transmission' =&amp;gt; 'automatic',
                    'price' =&amp;gt; '1000',
                    'fuel' =&amp;gt; 'petrol',
                    'mileage' =&amp;gt; 1000
                ])
                -&amp;gt;call('create')
                -&amp;gt;assertSet('image', $file-&amp;gt;name)
                -&amp;gt;assertHasNoErrors(['name', 'reg_num']);
                 Storage::disk('avatars')-&amp;gt;assertExists($file-&amp;gt;hashName());
                $this-&amp;gt;assertAuthenticatedAs($user);
                $this-&amp;gt;assertTrue(Auth::check());
                $this-&amp;gt;assertDatabaseHas('vehicles', [
                    'name' =&amp;gt; 'Toyota',
                    'reg_num' =&amp;gt; 'GD-123-12',
                    'vin_num' =&amp;gt; 'kajsy',
                    'serviced' =&amp;gt; null,
                    'status' =&amp;gt; true,
                    'home_away' =&amp;gt; true,
                    'transmission' =&amp;gt; 'automatic',
                    'price' =&amp;gt; 1000,
                    'fuel' =&amp;gt; 'petrol',
                ]);
                ob_get_contents();
                ob_end_clean();
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the code block above, we are writing a test to add a new vehicle record to the database. Now I have intentionally added code blocks to specifically throw &lt;code&gt;Error: Test code or tested code did not (only) close its own output buffers&lt;/code&gt;, which is `assertSet('image', $file).&lt;/p&gt;

&lt;p&gt;Let's take a look a the console when we run this test despite including &lt;code&gt;ob_start()&lt;/code&gt; and &lt;code&gt;ob_end_clean()&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;`&lt;br&gt;
There was 1 risky test:&lt;/p&gt;

&lt;p&gt;1) Tests\Unit\V1\Admin\Vehicle\VehicleTest::test_create_new_vehicle_entry_with_file_upload&lt;br&gt;
Test code or tested code did not (only) close its own output buffers&lt;/p&gt;

&lt;p&gt;F:\projects\Laravel\live2\tests\Unit\V1\Admin\Vehicle\VehicleTest.php:21&lt;/p&gt;

&lt;p&gt;FAILURES!&lt;br&gt;
Tests: 1, Assertions: 1, Failures: 1, Risky: 1.&lt;br&gt;
`&lt;/p&gt;

&lt;p&gt;The error message still isn't clearly stated, now I'm going to refactor the code and run the test.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;&lt;/code&gt;`&lt;br&gt;
    public function test_create_new_vehicle_entry_with_file_upload()&lt;br&gt;
    {&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    while (ob_get_level() &amp;gt; 0) {
        ob_end_clean();
    }
    Storage::fake('avatars');

    $user = User::factory()-&amp;gt;create();
    $this-&amp;gt;actingAs($user);
    Auth::login($user);

    $file = UploadedFile::fake()-&amp;gt;image('avatar.jpg');

    Livewire::test(Add::class)
            -&amp;gt;set([
                'name' =&amp;gt; 'Toyota',
                'reg_num' =&amp;gt; 'GD-123-12',
                'vin_num' =&amp;gt; 'kajsy',
                'status' =&amp;gt; true,
                'home_away' =&amp;gt; true,
                'image' =&amp;gt; $file,
                'transmission' =&amp;gt; 'automatic',
                'price' =&amp;gt; '1000',
                'fuel' =&amp;gt; 'petrol',
                'mileage' =&amp;gt; 1000
            ])
            -&amp;gt;call('create')
            -&amp;gt;assertSet('image', $file-&amp;gt;name)
            -&amp;gt;assertHasNoErrors(['name', 'reg_num']);
            Storage::disk('avatars')-&amp;gt;assertExists($file);
            $this-&amp;gt;assertAuthenticatedAs($user);
            $this-&amp;gt;assertTrue(Auth::check());
            $this-&amp;gt;assertDatabaseHas('vehicles', [
                'name' =&amp;gt; 'Toyota',
                'reg_num' =&amp;gt; 'GD-123-12',
                'vin_num' =&amp;gt; 'kajsy',
                'serviced' =&amp;gt; null,
                'status' =&amp;gt; true,
                'home_away' =&amp;gt; true,
                'transmission' =&amp;gt; 'automatic',
                'price' =&amp;gt; 1000,
                'fuel' =&amp;gt; 'petrol',
            ]);
            ob_get_contents();
            ob_end_clean();
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;`&lt;code&gt;&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;I have replaced &lt;code&gt;ob_start()&lt;/code&gt; with &lt;code&gt;ob_get_level()&lt;/code&gt; in a conditional statement that'll trigger &lt;code&gt;ob_end_clean()&lt;/code&gt; when it surpasses 0. Let's take a look at the error message.&lt;/p&gt;

&lt;p&gt;`&lt;br&gt;
PS F:\projects\Laravel\live2&amp;gt; ./vendor/bin/phpunit --filter=VehicleTest&lt;br&gt;
PHPUnit 10.0.11 by Sebastian Bergmann and contributors.&lt;/p&gt;

&lt;p&gt;Runtime:       PHP 8.2.0&lt;br&gt;
Configuration: F:\projects\Laravel\live2\phpunit.xml&lt;/p&gt;

&lt;p&gt;F                                                                   1 / 1 (100%)&lt;/p&gt;

&lt;p&gt;Time: 00:01.956, Memory: 42.00 MB&lt;/p&gt;

&lt;p&gt;There was 1 failure:&lt;/p&gt;

&lt;p&gt;1) Tests\Unit\V1\Admin\Vehicle\VehicleTest::test_create_new_vehicle_entry_with_file_upload&lt;br&gt;
Failed asserting that two strings are equal.&lt;br&gt;
--- Expected&lt;br&gt;
+++ Actual&lt;br&gt;
@@ @@&lt;br&gt;
-'avatar.jpg'&lt;br&gt;
+'livewire-file:RxzKXRUzs3bLTN9IHbWBFtHgfTLRb4-metaYXZhdGFyLmpwZw==--size=695.jpg'     &lt;/p&gt;

&lt;p&gt;F:\projects\Laravel\live2\vendor\livewire\livewire\src\Testing\Concerns\MakesAssertions.php:22&lt;br&gt;
F:\projects\Laravel\live2\tests\Unit\V1\Admin\Vehicle\VehicleTest.php:50&lt;br&gt;
F:\projects\Laravel\live2\vendor\laravel\framework\src\Illuminate\Foundation\Testing\TestCase.php:173&lt;/p&gt;

&lt;p&gt;FAILURES!&lt;br&gt;
Tests: 1, Assertions: 1, Failures: 1.&lt;br&gt;
`&lt;/p&gt;

&lt;p&gt;Now we get a clear error message that will allow us to properly Debug our code. &lt;/p&gt;

&lt;p&gt;Now that we have a clear understanding of how to handle the &lt;code&gt;Error: Test code or tested code did not (only) close its own output buffers&lt;/code&gt; issue, we'll be diving deeper into the topic of debugging in our next episode. We'll cover some essential tools and techniques that every developer should have in their toolkit to troubleshoot issues quickly and effectively. Stay tuned!&lt;/p&gt;

&lt;p&gt;Be sure to follow me on &lt;a href="'https://twitter.com/kwade_jeffrey'"&gt;twitter&lt;/a&gt;, github, showwcase at &lt;a class="mentioned-user" href="https://dev.to/rebelnii"&gt;@rebelnii&lt;/a&gt; and subscribe to my &lt;a href="https://www.youtube.com/@RebelBase596?sub_confirmation=1"&gt;YouTube&lt;/a&gt;&lt;/p&gt;

</description>
      <category>laravel</category>
      <category>testing</category>
      <category>tutorial</category>
      <category>webdev</category>
    </item>
    <item>
      <title>How to build a custom eloquent builder class in Laravel.</title>
      <dc:creator>Jeffrey Kwade</dc:creator>
      <pubDate>Wed, 05 Apr 2023 02:38:39 +0000</pubDate>
      <link>https://dev.to/rebelnii/how-to-build-a-custom-eloquent-builder-class-in-laravel-4bp8</link>
      <guid>https://dev.to/rebelnii/how-to-build-a-custom-eloquent-builder-class-in-laravel-4bp8</guid>
      <description>&lt;p&gt;In Laravel, Eloquent is the default ORM (Object-Relational Mapping) that provides an elegant and easy way to interact with the database. An Eloquent builder is a query builder that provides a convenient, fluent interface to create and run database queries.&lt;/p&gt;

&lt;p&gt;When you create a new instance of an Eloquent model, you can use its query builder methods to create and run queries. For example, you can use the "where" method to specify conditions for the query, the "orderBy" method to order the results, and the get method to retrieve the results.&lt;/p&gt;

&lt;p&gt;In addition to the basic query builder methods, the Eloquent builder also provides a number of advanced features, such as eager loading of related models, lazy loading of relationships, and support for polymorphic relationships. Overall, the Eloquent builder is a powerful tool that makes it easy to work with databases in Laravel.&lt;/p&gt;

&lt;p&gt;Let's dive into the code! In this example, we have a model called Bookings, where a user can make a reservation to rent out a company's vehicles. The goal is to fetch a user's reservation records and allow the user to filter the records based on whether the reservation was cancelled, if the user picked up the reserved vehicle, and a general search based on the name on the reservation or the email used for the reservation. To achieve this, we will create our first eloquent builder and improve upon it as we go along.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Booking::query()-&amp;gt;where('user_id', $this-&amp;gt;user_id)
    -&amp;gt;when($this-&amp;gt;cancelled != null, function($query){
        $query-&amp;gt;where('cancelled', filter_var($this-&amp;gt;cancelled, FILTER_VALIDATE_BOOLEAN));
    })
    -&amp;gt;when($this-&amp;gt;picked_up != null, function($query){
        $query-&amp;gt;where('confirm_pick', filter_var($this-&amp;gt;picked_up, FILTER_VALIDATE_BOOLEAN));
    })
    -&amp;gt;when($this-&amp;gt;search != '', function($query){
        $query-&amp;gt;where('name', "LIKE", "%{$this-&amp;gt;search}%")
                -&amp;gt;orWhere('email', 'LIKE', "%{$this-&amp;gt;search}%");
    })-&amp;gt;paginate(5)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Let me explain the code above.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;We begin the query builder by calling the model Booking and &lt;code&gt;query&lt;/code&gt; method &lt;code&gt;Booking::query()&lt;/code&gt;, this is how we start query builders in Laravel.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Then we add the &lt;code&gt;where&lt;/code&gt; method to add constraints which implies that we are looking for bookings where the &lt;code&gt;user_id&lt;/code&gt; matches the current user's id.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Next, &lt;code&gt;when($this-&amp;gt;cancelled != null, function($query){...})&lt;/code&gt; is a conditional statement using the when() method. If the &lt;code&gt;$cancelled&lt;/code&gt; property of the current class is not null, it will execute the function passed as the second argument. Inside the function, &lt;code&gt;$query&lt;/code&gt; represents the query builder instance. Here, we're adding another filter to the query builder where cancelled column should be equal to the boolean value of &lt;code&gt;$this-&amp;gt;cancelled&lt;/code&gt; property.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Similarly, &lt;code&gt;when($this-&amp;gt;picked_up != null, function($query){...})&lt;/code&gt; adds a filter to the query builder based on the &lt;code&gt;$picked_up&lt;/code&gt; property, and &lt;code&gt;when($this-&amp;gt;search != '', function($query){...})&lt;/code&gt; adds a filter based on the $search property.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;5.Finally, the paginate(5) method is used to paginate the results and limit the number of results per page to 5.&lt;/p&gt;

&lt;p&gt;So, this code generates a query to fetch the bookings where the &lt;code&gt;user_id&lt;/code&gt; is equal to the current user's &lt;code&gt;user_id&lt;/code&gt;, and then applies additional filters based on the values of $cancelled, $picked_up, and $search, before paginating the results. &lt;/p&gt;

&lt;p&gt;Now that we understand what the code means, let's clean up our code. Writing clean code has many benefits like:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Readability: Clean code is easier to read and understand, which helps other developers on the team to quickly grasp the code and make modifications if needed.&lt;/li&gt;
&lt;li&gt;Maintainability: Clean code is easier to maintain and update, which saves time and effort in the long run.&lt;/li&gt;
&lt;li&gt;Collaboration: Clean code promotes collaboration among developers as it is easier to understand and modify. This means that multiple developers can work on the same codebase without stepping on each other's toes.&lt;/li&gt;
&lt;li&gt;Debugging: Clean code makes debugging easier since it is easier to identify where errors or bugs may be located.&lt;/li&gt;
&lt;li&gt;Scalability: Clean code is more scalable since it is easier to add new features or functionality without introducing bugs or breaking existing code.&lt;/li&gt;
&lt;li&gt;Efficiency: Clean code is more efficient since it requires fewer resources to execute and runs faster, which can lead to improved performance and user experience.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;We are going to implements the scope approach to clean up the initial form of our code.&lt;/p&gt;

&lt;p&gt;In Laravel, a scope query is a reusable query constraint that can be applied to a model. It allows you to define a specific set of constraints for a query and reuse it in different parts of your application.&lt;/p&gt;

&lt;p&gt;You can define a scope query method in a model by prefixing its name with "scope".&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;?php

namespace App\Models;

use App\Builders\BookingsBuilder;
use App\Models\User;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Booking extends Model
{
    use HasFactory;

    protected $fillable = ['name', 'email', 'booking_date', 'pickup_date', 'return_date', 'confirm_pick', 'user_id', 'vehicle_id', 'total_price', 'num_days'];


    public function scopeCancelled($query, $cancelled)
    {
        return $query-&amp;gt;when($cancelled != null, function($q) use($cancelled){
            $q-&amp;gt;where('cancelled', filter_var($cancelled, FILTER_VALIDATE_BOOLEAN));
        });
    }

    public function scopePickedUp($query, $pickedUp)
    {
        return $query-&amp;gt;when($pickedUp != null, function($q) use($pickedUp){
            $q-&amp;gt;where('confirm_pick', filter_var($pickedUp, FILTER_VALIDATE_BOOLEAN));
        });
    }

    public function scopeSearch($query, $search)
    {
        return $query-&amp;gt;when($search != null, function($q) use($search){
            $q-&amp;gt;where('name', 'like', '%'.$search.'%')
                    -&amp;gt;orWhere('email', 'like', '%'.$search.'%');
        });
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The code above achieves the same goal as the original query builder, but with the added benefit of creating reusable methods that can be called on the model from anywhere in our application. This means we can avoid duplicating our code and have a more organized and efficient way of handling our queries.&lt;/p&gt;

&lt;p&gt;Let's take a look at what our current code looks like.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public function render()
    {
        return view('livewire.frontend.user-bookings', [
            'bookings' =&amp;gt; Booking::query()-&amp;gt;where('user_id', $this-&amp;gt;user_id)
                -&amp;gt;Cancelled( $this-&amp;gt;cancelled)
                -&amp;gt;PickedUp( $this-&amp;gt;picked_up)
                -&amp;gt;Search( $this-&amp;gt;search)
                -&amp;gt;paginate(5)
        ]);
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;It's much cleaner and more readable than its initial form. However, as you can see, our model class now has a lot of methods, which can make it messy and harder to maintain. To take it a step further, let's build a custom Eloquent builder class.&lt;/p&gt;

&lt;p&gt;When using Laravel's Eloquent ORM, it's common to define scopes on models to encapsulate commonly used query logic. This makes it easier to maintain and reuse queries across different parts of your application. However, as your application grows and you add more and more scopes to your models, it can become cluttered and difficult to manage.&lt;/p&gt;

&lt;p&gt;A solution to this problem is to use a custom Eloquent builder class. This class is responsible for building queries based on the defined scopes and filters, instead of putting all the logic in the model. This approach can help keep your models clean and focused on their main responsibilities, while also providing a more modular and testable codebase. By separating the query building logic from the model, you can also make it easier to reuse the queries across different models and even different projects.&lt;/p&gt;

&lt;p&gt;First, create a new class that extends Laravel's base &lt;code&gt;Illuminate\Database\Eloquent\Builder&lt;/code&gt; class and move all your methods from the model into this class:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;?php
namespace App\Builders;
use Illuminate\Database\Eloquent\Builder;



class BookingsBuilder extends Builder
{
    public function __construct($query)
    {
        parent::__construct($query);
    }

    public function Cancelled( $cancelled)
    {
        return $this-&amp;gt;when($cancelled != null, function($q) use($cancelled){
            $q-&amp;gt;where('cancelled', filter_var($cancelled, FILTER_VALIDATE_BOOLEAN));
        });
    }

    public function PickedUp( $pickedUp)
    {
        return $this-&amp;gt;when($pickedUp != null, function($q) use($pickedUp){
            $q-&amp;gt;where('confirm_pick', filter_var($pickedUp, FILTER_VALIDATE_BOOLEAN));
        });
    }

    public function Search( $search)
    {
        return $this-&amp;gt;when($search != null, function($q) use($search){
            $q-&amp;gt;where('name', 'like', '%'.$search.'%')
                    -&amp;gt;orWhere('email', 'like', '%'.$search.'%');
        });
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Next, update your model to use the new builder class:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;?php

namespace App\Models;

use App\Builders\BookingsBuilder;
use App\Models\User;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Booking extends Model
{
    use HasFactory;

    protected $fillable = ['name', 'email', 'booking_date', 'pickup_date', 'return_date', 'confirm_pick', 'user_id', 'vehicle_id', 'total_price', 'num_days'];

    public function newEloquentBuilder($query)
    {
        return new BookingsBuilder($query);
    }

    public function vehicle()
    {
        return $this-&amp;gt;belongsTo(Vehicle::class);
    }

    public function user()
    {
        return $this-&amp;gt;belongsTo(User::class);
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now our model is clean and easily readable.&lt;/p&gt;

&lt;p&gt;Thank you for reading and please be sure to follow me on my social media accounts &lt;a href="https://twitter.com/RebelNii"&gt;Twitter&lt;/a&gt;, &lt;a href="https://github.com/RebelNii"&gt;Github&lt;/a&gt;, &lt;a href="https://www.showwcase.com/rebelnii"&gt;showwcase&lt;/a&gt; and also subscribe to my &lt;a href="https://www.youtube.com/channel/UCdzJlunXysrx-HY69b3CblA"&gt;Youtube&lt;/a&gt;, I have a tutorial about this blog post on there.&lt;/p&gt;

</description>
      <category>laravel</category>
      <category>webdev</category>
      <category>tutorial</category>
      <category>database</category>
    </item>
    <item>
      <title>Let's Talk About HTTP-Client In Laravel.</title>
      <dc:creator>Jeffrey Kwade</dc:creator>
      <pubDate>Sun, 02 Apr 2023 22:37:15 +0000</pubDate>
      <link>https://dev.to/rebelnii/lets-talk-about-http-client-in-laravel-51j5</link>
      <guid>https://dev.to/rebelnii/lets-talk-about-http-client-in-laravel-51j5</guid>
      <description>&lt;p&gt;Laravel provides an easy-to-use interface for making HTTP requests to remote servers or APIs. Whether you need to send a GET request to retrieve data, a POST request to create or update data, or any other type of HTTP request, Laravel's HTTP client can handle it all.&lt;br&gt;
To make an HTTP request in Laravel, you can use the built-in HTTP client that utilizes Guzzle. This client offers a simple API for making requests, and it can handle things like setting headers, adding query parameters, and even sending JSON payloads.&lt;br&gt;
In addition to the basic HTTP client, Laravel also provides several other features to make working with HTTP requests even easier. For example, you can use middleware to modify requests or responses, and you can use the cache system to cache responses for improved performance.&lt;/p&gt;

&lt;p&gt;Sending HTTP requests to a RESTful API endpoint is a common task in web development. Laravel provides a convenient Http facade that allows developers to easily send HTTP requests using the GET, POST, PUT, PATCH, and DELETE methods.&lt;/p&gt;

&lt;p&gt;Let's take a closer look at how to use the Http facade in Laravel.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;use Illuminate\Support\Facades\Http;

$response = Http::get('https://rest.coinapi.io/v1/exchangerate/BTC/USD');

$response = Http::post('https://rest.coinapi.io/v1/exchangerate/BTC/USD', [
    'name' =&amp;gt; 'Steve',
    'role' =&amp;gt; 'Network Administrator',
]);

$response = Http::put('https://rest.coinapi.io/v1/exchangerate/BTC/USD', [
    'name' =&amp;gt; 'Steve',
    'role' =&amp;gt; 'Network Administrator',
]);

$response = Http::patch('https://rest.coinapi.io/v1/exchangerate/BTC/USD', [
    'name' =&amp;gt; 'Steve',
    'role' =&amp;gt; 'Network Administrator',
]);

$response = Http::delete('https://rest.coinapi.io/v1/exchangerate/BTC/USD', [
    'name' =&amp;gt; 'Steve',
]);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The get method returns an instance of Illuminate\Http\Client\Response, which provides a variety of methods that may be used to inspect the response.&lt;/p&gt;

&lt;p&gt;The following methods are available on the response object:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;body() returns the response body as a string.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;json($key = null, $default = null) returns the response body as an array or object.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;object() returns the response body as an object.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;collect($key = null) returns the response body as a collection.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;status() returns the HTTP status code of the response.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;successful() returns true if the HTTP status code is in the 200-299 range.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;redirect() returns true if the HTTP status code is in the 300-399 range.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;failed() returns true if the HTTP status code is in the 400-599 range.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;clientError() returns true if the HTTP status code is in the 400-499 range.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;header($header) returns the value of the specified HTTP header.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;headers() returns an array of HTTP headers.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;While sending HTTP requests to an external API endpoint, it's essential to handle errors that might occur. Laravel's Http facade provides a straightforward way to handle HTTP errors using the throw() method.&lt;br&gt;
For example, to throw an exception if the HTTP status code is not in the 200-299 range, you can use the following code:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;$response = Http::get('https://api.example.com');

$response-&amp;gt;throw();
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Laravel also provides a method to dump a request. This helps a developer to confirm that they are sending the intended parameters and headers. You may add the 'dd()' method to the beginning of your request definition:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Http::dd()-&amp;gt;withUrlParameters([
    'endpoint' =&amp;gt; 'https://api.example.com',
    'page' =&amp;gt; 'docs',
    'version' =&amp;gt; '9.x',
    'topic' =&amp;gt; 'validation',
])-&amp;gt;get('{+endpoint}/{page}/{version}/{topic}');
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now let's make a GET request to coinapi and dump the response body.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;"""
{


  "time": "2023-04-02T18:19:49.0000000Z",


  "asset_id_base": "BTC",


  "asset_id_quote": "USD",


  "rate": 28192.38334862458369820384358


}
""" // app\Http\Livewire\Admin\Admin.php:24
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The Http response in Laravel also implements PHP's array access allowing us to directly access json response data.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;Http::accept('application/json')-&amp;gt;withHeaders([&lt;br&gt;
            'X-CoinAPI-Key' =&amp;gt; 'Example'&lt;br&gt;
        ])-&amp;gt;get('https://rest.coinapi.io/v1/exchangerate/BTC/USD')['rate'];&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;In our HTTP request, we added the acceptJson method to quickly specify that our application expects the application/json content type in response to our request, as well as the withHeaders method. This withHeaders method accepts an array of key/value pairs.&lt;/p&gt;

&lt;p&gt;After making the HTTP GET request, let's dump our response:&lt;/p&gt;

&lt;p&gt;&lt;code&gt;28212.751030531 // app\Http\Livewire\Admin\Admin.php:24&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;we easily grab our desired data with less code.&lt;/p&gt;

&lt;p&gt;If you would like, you may use the withToken method to quickly add a bearer token to the request's Authorization header:&lt;br&gt;
&lt;code&gt;$response = Http::withToken('token-key')-&amp;gt;post(/* ... */);&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;In conclusion, the HTTP facade allows a developer to easily make HTTP requests in an efficient and clean manner compared to other methods of making HTTP requests in PHP.&lt;/p&gt;

&lt;p&gt;Let's compare the HttpRequest in PHP to Laravel's HTTP facade:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;?php
$request = new HttpRequest();
$request-&amp;gt;setUrl('https://rest.coinapi.io/v1/exchangerate/BTC/USD');
$request-&amp;gt;setMethod(HTTP_METH_GET);
$request-&amp;gt;setHeaders(array(
  'X-CoinAPI-Key' =&amp;gt; '73034021-THIS-IS-SAMPLE-KEY'
));

try {
  $response = $request-&amp;gt;send();
  echo $response-&amp;gt;getBody();
} catch (\HttpException $ex) {
  echo $ex;
}
?&amp;gt;

&amp;lt;?php

Http::accept('application/json')-&amp;gt;withHeaders([
            'X-CoinAPI-Key' =&amp;gt; 'Example'
        ])-&amp;gt;get('https://rest.coinapi.io/v1/exchangerate/BTC/USD')['rate'];


?&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We have a shorter and cleaner code syntax when implementing Laravel's Http request compared to PHP's HttpRequest api.&lt;/p&gt;

&lt;p&gt;These are just a few use cases for the Http facade in laravel, take a look through &lt;a href="https://laravel.com/docs/10.x/http-client"&gt;Laravel's documentation&lt;/a&gt; for a comprehensive list of options available with the Http facade.&lt;/p&gt;

&lt;p&gt;Thank you for taking the time to read this post. For more tips and tutorials on web development, feel free to follow me on &lt;a href="https://twitter.com/RebelNii"&gt;twitter&lt;/a&gt;, &lt;a href="https://github.com/RebelNii"&gt;github&lt;/a&gt; and subscribe to my &lt;a href="https://www.youtube.com/@RebelBase596"&gt;youtube&lt;/a&gt;. &lt;/p&gt;

</description>
      <category>webdev</category>
      <category>laravel</category>
      <category>tutorial</category>
      <category>php</category>
    </item>
    <item>
      <title>How to create a dynamic fixed navigation system on a web page.</title>
      <dc:creator>Jeffrey Kwade</dc:creator>
      <pubDate>Wed, 29 Mar 2023 11:51:33 +0000</pubDate>
      <link>https://dev.to/rebelnii/how-to-create-a-dynamic-fixed-navigation-system-on-a-web-page-1a6h</link>
      <guid>https://dev.to/rebelnii/how-to-create-a-dynamic-fixed-navigation-system-on-a-web-page-1a6h</guid>
      <description>&lt;p&gt;Hello devs,&lt;/p&gt;

&lt;p&gt;I have a simple but useful topic to blog about so lend me your time, I promise it will be worth it.&lt;/p&gt;

&lt;p&gt;We will be looking at how to render a dynamic navbar on a web application. Our navbar will start out as a block element and we'll dynamically change it to a fixed element when to scroll down our Y-Axis of our window using JavaScript. &lt;/p&gt;

&lt;p&gt;This will be our html template:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;!DOCTYPE html&amp;gt;
&amp;lt;html lang="en"&amp;gt;
&amp;lt;head&amp;gt;
    &amp;lt;meta charset="UTF-8"&amp;gt;
    &amp;lt;meta http-equiv="X-UA-Compatible" content="IE=edge"&amp;gt;
    &amp;lt;meta name="viewport" content="width=device-width, initial-scale=1.0"&amp;gt;
    &amp;lt;link rel="stylesheet" href="style.css"&amp;gt;
    &amp;lt;title&amp;gt;Rebelbase&amp;lt;/title&amp;gt;
&amp;lt;/head&amp;gt;
&amp;lt;body&amp;gt;
    &amp;lt;div id="container"&amp;gt;
        &amp;lt;nav id="nav" class="block"&amp;gt;
            &amp;lt;div class=""&amp;gt;
                &amp;lt;h1&amp;gt;Fixed Navigation&amp;lt;/h1&amp;gt;
            &amp;lt;/div&amp;gt;
            &amp;lt;div class="list"&amp;gt;
                &amp;lt;ul&amp;gt;
                    &amp;lt;li&amp;gt;Home&amp;lt;/li&amp;gt;
                    &amp;lt;li&amp;gt;Profile&amp;lt;/li&amp;gt;
                    &amp;lt;li&amp;gt;Cart&amp;lt;/li&amp;gt;
                    &amp;lt;li&amp;gt;Logout&amp;lt;/li&amp;gt;
                &amp;lt;/ul&amp;gt;
            &amp;lt;/div&amp;gt;
        &amp;lt;/nav&amp;gt;
        &amp;lt;main&amp;gt;
            &amp;lt;section class="section"&amp;gt;
                &amp;lt;h1 class="h1"&amp;gt;Section One&amp;lt;/h1&amp;gt;
                &amp;lt;article class="art"&amp;gt;
                    Lorem ipsum, dolor sit amet consectetur adipisicing elit. Quidem animi placeat minus ipsa nisi nostrum velit, officiis neque soluta possimus aliquid, commodi ad maiores laudantium quae, dolore repudiandae facilis qui.
                    Quo dolor inventore aspernatur quis, delectus impedit cupiditate numquam porro est dolore laudantium nisi ratione magni quasi alias, vero soluta atque rerum temporibus natus eius pariatur. Distinctio impedit minima reprehenderit!
                    Earum, facilis id? Accusamus veritatis voluptates corporis rem mollitia odio iste earum animi amet fugit, ipsa architecto totam soluta accusantium! Delectus, rem consequuntur omnis inventore voluptate laborum! Necessitatibus, atque cum.
                    Ducimus, excepturi. Beatae atque quas iste commodi vel, neque corrupti asperiores nostrum maiores ipsa laudantium assumenda odio ipsum, nam a laboriosam amet quisquam, facere veritatis. Saepe ipsum dolorum aut deserunt?
                    Rem, quam saepe numquam reiciendis sunt corrupti esse, veniam iste delectus officiis inventore excepturi repellat culpa cumque quas. Eos voluptas eveniet sunt ad aperiam nulla nobis non ratione, adipisci cumque!
                    Odit nostrum molestias, facere officia fugiat ipsam fugit voluptates dolore eaque necessitatibus nesciunt sed beatae. Eum quidem, totam necessitatibus eius aperiam neque ex esse labore nihil sequi facilis, dicta molestias!
                    Harum dolor dolorum illum et expedita repellendus dicta, nemo recusandae sequi suscipit ut necessitatibus labore consequatur sunt quam, modi aliquid reprehenderit esse. Dolores alias, illum recusandae temporibus harum voluptates atque.
                    Ducimus quaerat earum perspiciatis doloribus, alias suscipit nobis esse officiis voluptate magnam non maiores eos ex, dolor quis pariatur corrupti sed dolorum fugiat dignissimos? Ratione eveniet fugiat ea. Sint, mollitia!
                    Minima hic eaque distinctio, consequatur cupiditate autem numquam laboriosam, molestiae soluta quidem laudantium? Quam asperiores soluta temporibus in aliquam accusamus doloribus explicabo animi ad, quibusdam nemo tenetur ipsum amet aspernatur.
                    Sed distinctio quidem, odit reiciendis alias error exercitationem placeat voluptates at dolore? Voluptate adipisci quod assumenda possimus. Nostrum error ut illum incidunt iste doloremque suscipit corrupti ex nesciunt nobis. Culpa.
                &amp;lt;/article&amp;gt;
            &amp;lt;/section&amp;gt;
            &amp;lt;section class="section"&amp;gt;
                &amp;lt;h1 class="h1"&amp;gt;Section Two&amp;lt;/h1&amp;gt;
                &amp;lt;article class="art"&amp;gt;
                    Lorem ipsum, dolor sit amet consectetur adipisicing elit. Quidem animi placeat minus ipsa nisi nostrum velit, officiis neque soluta possimus aliquid, commodi ad maiores laudantium quae, dolore repudiandae facilis qui.
                    Quo dolor inventore aspernatur quis, delectus impedit cupiditate numquam porro est dolore laudantium nisi ratione magni quasi alias, vero soluta atque rerum temporibus natus eius pariatur. Distinctio impedit minima reprehenderit!
                    Earum, facilis id? Accusamus veritatis voluptates corporis rem mollitia odio iste earum animi amet fugit, ipsa architecto totam soluta accusantium! Delectus, rem consequuntur omnis inventore voluptate laborum! Necessitatibus, atque cum.
                    Ducimus, excepturi. Beatae atque quas iste commodi vel, neque corrupti asperiores nostrum maiores ipsa laudantium assumenda odio ipsum, nam a laboriosam amet quisquam, facere veritatis. Saepe ipsum dolorum aut deserunt?
                    Rem, quam saepe numquam reiciendis sunt corrupti esse, veniam iste delectus officiis inventore excepturi repellat culpa cumque quas. Eos voluptas eveniet sunt ad aperiam nulla nobis non ratione, adipisci cumque!
                    Odit nostrum molestias, facere officia fugiat ipsam fugit voluptates dolore eaque necessitatibus nesciunt sed beatae. Eum quidem, totam necessitatibus eius aperiam neque ex esse labore nihil sequi facilis, dicta molestias!
                    Harum dolor dolorum illum et expedita repellendus dicta, nemo recusandae sequi suscipit ut necessitatibus labore consequatur sunt quam, modi aliquid reprehenderit esse. Dolores alias, illum recusandae temporibus harum voluptates atque.
                    Ducimus quaerat earum perspiciatis doloribus, alias suscipit nobis esse officiis voluptate magnam non maiores eos ex, dolor quis pariatur corrupti sed dolorum fugiat dignissimos? Ratione eveniet fugiat ea. Sint, mollitia!
                    Minima hic eaque distinctio, consequatur cupiditate autem numquam laboriosam, molestiae soluta quidem laudantium? Quam asperiores soluta temporibus in aliquam accusamus doloribus explicabo animi ad, quibusdam nemo tenetur ipsum amet aspernatur.
                    Sed distinctio quidem, odit reiciendis alias error exercitationem placeat voluptates at dolore? Voluptate adipisci quod assumenda possimus. Nostrum error ut illum incidunt iste doloremque suscipit corrupti ex nesciunt nobis. Culpa.
                &amp;lt;/article&amp;gt;
            &amp;lt;/section&amp;gt;
            &amp;lt;section class="section"&amp;gt;
                &amp;lt;h1 class="h1"&amp;gt;Section Three&amp;lt;/h1&amp;gt;
                &amp;lt;article class="art"&amp;gt;
                    Lorem ipsum, dolor sit amet consectetur adipisicing elit. Quidem animi placeat minus ipsa nisi nostrum velit, officiis neque soluta possimus aliquid, commodi ad maiores laudantium quae, dolore repudiandae facilis qui.
                    Quo dolor inventore aspernatur quis, delectus impedit cupiditate numquam porro est dolore laudantium nisi ratione magni quasi alias, vero soluta atque rerum temporibus natus eius pariatur. Distinctio impedit minima reprehenderit!
                    Earum, facilis id? Accusamus veritatis voluptates corporis rem mollitia odio iste earum animi amet fugit, ipsa architecto totam soluta accusantium! Delectus, rem consequuntur omnis inventore voluptate laborum! Necessitatibus, atque cum.
                    Ducimus, excepturi. Beatae atque quas iste commodi vel, neque corrupti asperiores nostrum maiores ipsa laudantium assumenda odio ipsum, nam a laboriosam amet quisquam, facere veritatis. Saepe ipsum dolorum aut deserunt?
                    Rem, quam saepe numquam reiciendis sunt corrupti esse, veniam iste delectus officiis inventore excepturi repellat culpa cumque quas. Eos voluptas eveniet sunt ad aperiam nulla nobis non ratione, adipisci cumque!
                    Odit nostrum molestias, facere officia fugiat ipsam fugit voluptates dolore eaque necessitatibus nesciunt sed beatae. Eum quidem, totam necessitatibus eius aperiam neque ex esse labore nihil sequi facilis, dicta molestias!
                    Harum dolor dolorum illum et expedita repellendus dicta, nemo recusandae sequi suscipit ut necessitatibus labore consequatur sunt quam, modi aliquid reprehenderit esse. Dolores alias, illum recusandae temporibus harum voluptates atque.
                    Ducimus quaerat earum perspiciatis doloribus, alias suscipit nobis esse officiis voluptate magnam non maiores eos ex, dolor quis pariatur corrupti sed dolorum fugiat dignissimos? Ratione eveniet fugiat ea. Sint, mollitia!
                    Minima hic eaque distinctio, consequatur cupiditate autem numquam laboriosam, molestiae soluta quidem laudantium? Quam asperiores soluta temporibus in aliquam accusamus doloribus explicabo animi ad, quibusdam nemo tenetur ipsum amet aspernatur.
                    Sed distinctio quidem, odit reiciendis alias error exercitationem placeat voluptates at dolore? Voluptate adipisci quod assumenda possimus. Nostrum error ut illum incidunt iste doloremque suscipit corrupti ex nesciunt nobis. Culpa.
                &amp;lt;/article&amp;gt;
            &amp;lt;/section&amp;gt;
        &amp;lt;/main&amp;gt;
    &amp;lt;/div&amp;gt;

    &amp;lt;script src="index.js"&amp;gt;&amp;lt;/script&amp;gt;
&amp;lt;/body&amp;gt;
&amp;lt;/html&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The focus of this blog will be on our "nav" element that currently has an id of nav and a class of block.&lt;/p&gt;

&lt;p&gt;Let's take a look at the css I have applied:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;*{
    margin: 0;
    box-sizing: border-box;
    padding: 0;
    overflow-x: hidden;
}


body{
    width: 100%;
    height: 100%;
}

#container{
    width: 100%;
    min-height: 100vh;
}

#container .block{
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 14px;
    background: lightcoral;
    transition: all 500ms ease-in-out;
}

#container .fixed {
    position: fixed;
    display: flex;
    justify-content: space-between;
    align-items: center;
    top: 0;
    left: 0;
    right: 0;
    padding: 14px;
    z-index: 10;
    background: lightcoral;
    transition: all 500ms ease-in-out;
}

#container nav .list ul{
    display: flex;
    justify-content: center;
    align-items: center;
    gap: 4px;
}

#container nav .list ul li{
    list-style: none;
    cursor: pointer;
}


#container main .section {
    padding: 13px 8px;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The idea here is to dynamic change the class of our nav element from block to fixed using JavaScript, I have already applied css attributes to these two class.&lt;/p&gt;

&lt;p&gt;Now let's focus on the fun bit.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;window.addEventListener('scroll', () =&amp;gt; {
    /**
     * I'm setting a scroll event on the window
     * Then assign var currentScrollPosition the value of window.pageYOffset
     * window.pageYOffset will help us track the current position on our Y-axis
     * When we're at the very top of our window, y-axis will be 0
     * and the value will increase as we scroll down the window page.
     * The moment move from point 0, we'll swap the block class with the fixed class
     * 
     */
    let currentScrollPosition = window.pageYOffset;
    let nav = document.getElementById('nav');
    if(nav &amp;amp;&amp;amp; currentScrollPosition &amp;gt; 0){
        nav.classList.remove('block');
        nav.classList.add('fixed');
    }else{
        nav.classList.remove('fixed');
        nav.classList.add('block');
    }

    console.log(currentScrollPosition)

})
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Allow me to explain why I included the "nav" element in the if conditional statement.&lt;/p&gt;

&lt;p&gt;In building complex web applications, we often have multiple layouts catering to different user types, such as guests, authenticated users, and administrators. Therefore, our navbar may not always be present, resulting in an error in the console. The conditional statement is used to prevent this error from occurring.&lt;/p&gt;

&lt;p&gt;However, I must note that this method is primarily intended for beginners. Experienced developers would typically use frameworks like Vue.js, React, Alpine.js, Laravel, and Tailwind CSS, which provide easy implementation of this feature&lt;/p&gt;

&lt;p&gt;You can watch a &lt;a href="https://www.youtube.com/watch?v=pPXg23oMWec"&gt;youTube&lt;/a&gt; tutorial, please subscribe and be sure to follow me on &lt;a href="https://twitter.com/RebelNii"&gt;twitter&lt;/a&gt;, &lt;a href="https://github.com/RebelNii"&gt;gitHub&lt;/a&gt;, &lt;a href="https://www.showwcase.com/rebelnii"&gt;showwcase&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Thank you for your time,&lt;br&gt;
Jeffrey.&lt;/p&gt;

</description>
      <category>webdev</category>
      <category>javascript</category>
      <category>beginners</category>
      <category>tutorial</category>
    </item>
    <item>
      <title>Creating Laravel Blade Directive</title>
      <dc:creator>Jeffrey Kwade</dc:creator>
      <pubDate>Sat, 25 Mar 2023 15:27:34 +0000</pubDate>
      <link>https://dev.to/rebelnii/creating-laravel-blade-directive-4e87</link>
      <guid>https://dev.to/rebelnii/creating-laravel-blade-directive-4e87</guid>
      <description>&lt;p&gt;Hello fellow developers,&lt;/p&gt;

&lt;p&gt;I'll be talking about creating your very own custom blade directives in Laravel.&lt;/p&gt;

&lt;p&gt;Let's begin by explaining what blade directives are.&lt;/p&gt;

&lt;p&gt;Laravel Blade directives are a powerful feature of the Laravel PHP framework that allows developers to write clean and concise templates with minimal boilerplate code. Here are some of the most commonly used Laravel Blade directives:&lt;/p&gt;

&lt;p&gt;@if, &lt;a class="mentioned-user" href="https://dev.to/else"&gt;@else&lt;/a&gt;, @elseif: These directives allow developers to conditionally display content based on a given condition.&lt;/p&gt;

&lt;p&gt;&lt;a class="mentioned-user" href="https://dev.to/foreach"&gt;@foreach&lt;/a&gt;: This directive allows developers to loop through an array or collection and display content for each item.&lt;/p&gt;

&lt;p&gt;&lt;a class="mentioned-user" href="https://dev.to/include"&gt;@include&lt;/a&gt;: This directive allows developers to include a partial view file within a parent view file, making it easy to reuse common markup across multiple pages.&lt;/p&gt;

&lt;p&gt;@extends, @yield, @section: These directives allow developers to define a master layout file and inject content into specific sections of that layout from child views.&lt;/p&gt;

&lt;p&gt;&lt;a class="mentioned-user" href="https://dev.to/auth"&gt;@auth&lt;/a&gt;, @guest: These directives allow developers to conditionally display content based on the user's authentication status.&lt;/p&gt;

&lt;p&gt;@csrf: This directive generates a hidden input field with a CSRF token, which can help protect your application against cross-site request forgery attacks.&lt;/p&gt;

&lt;p&gt;Laravel Blade directives are easy to learn and use, and they can help developers write clean, maintainable, and efficient code.&lt;/p&gt;

&lt;p&gt;Now that we have that settled, let's create our custom blade directive.&lt;/p&gt;

&lt;p&gt;We will be creating the @admin blade directive, this directive allows me to render an html element(s) only when a user is has administrative privileges.&lt;/p&gt;

&lt;p&gt;We shall begin moving to the User model and create a method named "isAdmin".&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public function isAdmin()
{
    return $this-&amp;gt;is_admin == true;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;After we have successfully created this method, let's switch to the AppServiceProvider file, locate the boot function and let's register a function.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;use Illuminate\Support\Facades\Blade;

public function boot(): void
{
    Blade::if('admin', function(){
            return auth()-&amp;gt;user()-&amp;gt;isAdmin();
        });
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Make sure to import the blade facade. The first parameter of the blade facade is the name we are giving to the blade directive and the second parameter is a callabck function that simply returns the method we created within the User model.&lt;/p&gt;

&lt;p&gt;Now Let's use our newly created @admin blade directive.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;div class="flex justify-end"&amp;gt;
    @auth
        &amp;lt;div class="flex items-center gap-2"&amp;gt;
             @admin
                  &amp;lt;a href="/admin" class=""&amp;gt;Admin&amp;lt;/a&amp;gt;
             @endadmin
                 &amp;lt;livewire:auth.logout /&amp;gt;
        &amp;lt;/div&amp;gt;
      @else
         &amp;lt;a href="/login"&amp;gt;Login&amp;lt;/a&amp;gt; &amp;amp;nbsp;/&amp;amp;nbsp; 
         &amp;lt;a href="/register"&amp;gt;Register&amp;lt;/a&amp;gt;
     @endauth
&amp;lt;/div&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If the current user has administrative privileges, the admin navigation link will be rendered.&lt;/p&gt;

&lt;p&gt;Thank you for reading. &lt;br&gt;
I'm Jeffrey Kwade, follow me on &lt;a href="https://twitter.com/RebelNii"&gt;Twitter&lt;/a&gt;, &lt;a href="https://github.com/RebelNii"&gt;Github&lt;/a&gt; and subscribe to my new &lt;a href="https://www.youtube.com/@RebelBase596"&gt;Youtube&lt;/a&gt; channel&lt;/p&gt;

</description>
      <category>php</category>
      <category>laravel</category>
      <category>webdev</category>
      <category>programming</category>
    </item>
  </channel>
</rss>
