- Laravel -

Laravel Blade Directives: Class, Errors, Helpers, JS, JSON, PHP, Use, and Style

|
5 min read
...

Laravel provides a variety of Blade directives to simplify common tasks in your Blade templates. In this article, we'll explore several useful Blade directives for working with CSS classes, error messages, JavaScript variables, JSON data, PHP code, and more. These directives help you write cleaner, more expressive Blade templates and streamline your development workflow.

1. Class Directive @class

Introduced in Laravel 8.x, the @class directive simplifies the process of conditionally adding classes to HTML elements. It works by taking an associative array of class names and their corresponding conditions. If the condition is true, the class is added to the element; otherwise, it is omitted.

This feature streamlines the styling of HTML elements in Blade templates, making it more intuitive to manage class modifications dynamically.

2. Errors Directive @errors

These directives are used to display validation error messages associated with a specific form field. They work in conjunction with Laravel's form request validation system.

  1. Error Bag Check (@error):
    • The @error directive takes an optional argument (field name) within parentheses.
    • It checks if there's an error message for the specified field (or all errors if no argument is provided) in the current validation error bag.
  2. Error Message Display ({{ $message }}):
    • If there's an error message, the content between @error and @enderror is rendered.
    • Within this block, you can access the error message using {{ $message }}.
  3. Closing (@enderror):
    • The @enderror directive marks the end of the conditional block for displaying error messages.

As shown in the example, you can also use @else directive to have more control. By effectively using @error and @enderror, you can create user-friendly forms that provide clear and informative feedback in case of validation errors, guiding users towards valid data input.

3. Helpers Directive

Die and Dump - @dd()

  • Used for debugging purposes.
  • Prints the contents of a variable or expression within parentheses to the browser.
  • Stops the script execution after displaying the information.
  • Helpful for inspecting variable values during development to identify issues.

Dump - @dump()

  • Similar to@dd(), but allows script execution to continue after displaying the variable information.
  • Useful for debugging when you need to see variable values but also want the script to complete its normal execution.

CSRF - @csrf

  • Generates a Cross-Site Request Forgery (CSRF) protection token.
  • Used within forms to prevent unauthorized form submissions.
  • Laravel automatically handles token verification on form submission.

Method - @method()

  • Allows you to override the HTTP method (like POST or GET) associated with a form.
  • Useful when you need a form to submit data using a different method than the default form method (GETfor standard forms,POSTfor forms with data changes).

Vite - @vite()

  • This directive is used to import JavaScript or CSS assets from your project's source code into the Blade template.
  • Takes the path to the asset file (relative to theresources/jsdirectory) as an argument within parentheses.
  • Vite handles bundling the asset and injects it into the rendered HTML, ensuring proper inclusion of your JavaScript or CSS files.

4. JS Directive @js

The @js() blade directive was introduced to properly escape JSON within HTML quotes. It’s quite useful when we want to safely embed Javascript code within Blade Templates, especially when dealing with JSON data. This directive leverages the Js class introduced in Laravel 8.70 to achieve this functionality.

This allows us to seamlessly pass PHP variables containing JSON data to our JavaScript code in Laravel Blade templates without worrying about the escaping issues. This directive is very handy when working with front-end frameworks like Alpine.js, where we need to initialize data from our backend.

5. JSON Directive @json

The @json() directive is used to convert PHP data into JSON format directly within Blade templates. This directive is particularly useful when we need to pass data from our PHP backend to our JavaScript front-end.

However, the latest versions of Laravel provides us easy access to this functionality within our Blade templates using the Js facade.

let data = {{ Js::from($data) }};

6. PHP Directive @php

The @php directive allows us to embed raw PHP code directly within out Blade templates, providing a concise and readable way to execute PHP logic and manipulate data before the final HTML is rendered.

However, @php directive usage is discouraged in modern Laravel development due to concern about the separation of concerns, making view dumb, and the availability of more structured alternatives like Blade Components and Controller for handling complex logics.

7. Use Directive @use

Sometimes, we need to import the class name with its namespace, directly in out blade views. For that, we can use @use() blade directive to simplify the process of importing PHP classes directly into Blade templates.

This directive also accepts the second argument which could be used as alias for the imported class.

8. Style Directive @style

The @style directive can be used to dynamically apply inline CSS styles to our HTML element.

Conclusion

In this article, we explored several useful Blade directives that can help you write cleaner, more expressive Blade templates in Laravel. By leveraging these directives, you can streamline your development workflow, improve code readability, and simplify common tasks such as working with CSS classes, error messages, JavaScript variables, JSON data, PHP code, and more. Laravel's Blade templating engine provides a powerful set of tools to enhance your development experience and create dynamic, interactive web applications with ease.

If you have any questions or need further clarification on any of the topics discussed in this article, feel free to reach out to me. I'll be happy to help you out.

Keep coding, keep exploring, and keep inspiring. 🐼

Written By Anuz Pandey

Anuz Pandey is a multi-disciplinary designer and developer with a passion for creating visually stunning and user-friendly digital experiences. He has been working in the industry for over 5 years. He is currently working as a freelance designer and developer and is available for hire.

Tags

  • Laravel
  • Laravel Loops
  • Laravel Blade
  • Laravel Blade Directives