How to show new line in Laravel Blade? [SOLVED]


Steve Alila

Laravel

Laravel Blade is a powerful templating engine that comes bundled with the Laravel framework, which is widely used for web application development. It provides an intuitive syntax for creating and rendering views in a web application. One of the key features of Laravel Blade is its ability to handle new line characters in HTML output.

When creating HTML content, it's often necessary to include line breaks or new lines for better readability and organization. However, including new line characters directly in HTML can result in unexpected and undesirable formatting issues. Laravel Blade provides a simple and effective way to handle new lines in HTML output, allowing developers to create clean, readable, and well-organized HTML content without the risk of unexpected formatting issues. In this article, we'll explore how to use Laravel Blade to show new lines in HTML and improve the readability of your web application's views.

 

Laravel Blade syntax for displaying text and HTML elements

Blade is a templating engine that allows developers to write clean, readable, and reusable code for their web applications. Blade syntax uses curly braces {} to indicate expressions that should be evaluated and processed by the Blade engine.

To display text in Blade, you can simply use double curly braces {{ }} and put the text you want to display inside them. For example:

<p>Hello, {{ $name }}!</p>

In this example, the variable $name will be evaluated and its value will be displayed inside the HTML paragraph element.

To display HTML elements, you can use the {!! !!} syntax. For example:

{!! $html !!}

In this example, the variable $html will be evaluated and its value, which is an HTML code, will be displayed as it is, without escaping any HTML tags.

Blade also supports control structures such as if statements, loops, and switches. Here's an example of an if statement in Blade:

@if (count($items) > 0)
    <ul>
        @foreach ($items as $item)
            <li>{{ $item }}</li>
        @endforeach
    </ul>
@else
    <p>No items found.</p>
@endif

In this example, Blade checks if the $items array has any items, and if it does, it loops through them and displays them in an unordered list. If there are no items, it displays a message saying "No items found."

 

Displaying New Lines using the nl2br function

The nl2br function is a PHP function that replaces newline characters (\n) with HTML line break tags (<br>). In Blade, you can use the nl2br function to display new lines in HTML by passing a string variable through the function.

You can show a new line in HTML in the Laravel blade using the nl2br and e functions.

{{ nl2br(e($text)) }}

nl2br stands for newline-to-break. It converts the PHP newline \n to HTML br tag. e is a helper function running htmlentities on $text string. It purifies and escapes the character before passing them to the nl2br function.

Some Laravel versions may require you to surround the nl2br function with single curly braces and double exclamation marks instead of double curly braces.

{!! nl2br(e($text)) !!}

The concept is applied in WYSIWYG editors. Otherwise, like in HTML, Laravel blade will append new content to the current line despite you intending contrarily.

Here's another example that demonstrates the use of nl2br with a loop:

<ul>
    @foreach ($items as $item)
        <li>{{ nl2br($item->description) }}</li>
    @endforeach
</ul>

In this example, we are looping through an array of $items and displaying each item's description field with new lines properly formatted. The nl2br function is used to replace any newline characters in the description field with HTML line break tags.

 

Formatting Text with HTML Tags and CSS Classes

Blade allows you to use HTML tags and CSS classes to format your text. You can include any valid HTML tags and CSS classes in your Blade templates to format your text as desired.

For example, you can use HTML tags such as <b>, <i>, <u>, and <br> to format your text, like this:

<p>This is <b>bold</b> and this is <i>italic</i>.<br>This is <u>underlined</u>.</p>

In this example, the text inside the <b> tags will be displayed in bold, the text inside the <i> tags will be displayed in italic, and the text inside the <u> tags will be underlined. The <br> tag will create a new line.

You can also use CSS classes to style your text. For example:

<p class="large-text">This is some large text.</p>

In this example, the large-text class is used to apply a larger font size to the text in the paragraph.

 

Setup Lab Environment

Install and cd into the Laravel project before opening it with your code editor. 

laravel new blade_newline
cd blade_newline
code .

I have created blade_newline project and opened it with Visual Studio Code.

 

Create Migration

Next, make Post model with a migration file

php artisan make:model Post -m

then describe the schema.

// database/migrations/<post_table>.php
<?php
...
    public function up(): void
    {
        Schema::create('posts', function (Blueprint $table) {
            $table->id();
            $table->text('body');
            $table->timestamps();
        });
    }
...

Now create the database and migrate the changes.

php artisan migrate

Create Routes

Open the routes/web.php file and insert the following code.

<?php

use Illuminate\Support\Facades\Route;
use App\Models\Post;
use Illuminate\Http\Request;

Route::get('/', function () {
    $post = Post::find(1);
    return view('welcome', compact('post'));
});

Route::post('/create', function (Request $request) {
    $post = new Post();
    $post->body = $request->body;
    $post->save();
    return redirect('/');
});

We create the post via the /create endpoint and view it via the / endpoint. 

 

Example - Laravel blade show new line HTML

Create a form in the resources/views/welcome.blade.php file. 

...
<form action="{{ url('/create') }}" method="post">
  @csrf 
  <textarea name="body" class="bg-gray-100 p-2 w-full h-48 mb-2"></textarea>
  <button class="bg-gray-300 rounded px-3 py-1">Save</button>
</form>         
...

We collect long text through the body name and send it to thecreate route for saving to the database. Once a post is saved, we can collect and display it on the home page.

Input

...
<div class="m-10">
  @if ($post)
  {!! nl2br(e($post->body)) !!}
  @endif
</div>
...

Start the development server.

php artisan serve

and create a post with the following content.

What is Lorem Ipsum?

Lorem Ipsum is simply dummy text of the printing and typesetting industry.

Why do we use it?

It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout.

How to show new line in Laravel Blade? [SOLVED]

 

Output

laravel blade show new line html

 

Conclusion

Blade is a templating engine used in Laravel, a PHP web application framework. It allows developers to write clean and efficient code by providing a simple syntax for defining templates. To display new lines in HTML using Blade, developers can use the nl2br() function, which converts newline characters to HTML line breaks.

Here are some additional tips and resources for using Blade and HTML line breaks:

  • To add a newline character in a Blade template, use the "\n" escape sequence.
  • To add multiple line breaks, use the nl2br() function with the "\n" escape sequence concatenated multiple times.
  • The nl2br() function should be used with caution, as it can allow users to inject malicious code into a web page. Developers should always sanitize user input before using it in a template.
  • Laravel's official documentation provides extensive information on Blade templating, including how to use line breaks.
  • The Laravel community has created numerous resources, such as tutorials and packages, to help developers use Blade effectively.

 

Views: 86

Steve Alila

He specializes in web design, WordPress development, and data analysis, with proficiency in Python, JavaScript, and data extraction tools. Additionally, he excels in web API development, AI integration, and data presentation using Matplotlib and Plotly. You can connect with him on LinkedIn or check his projects on GitHub page.

Can't find what you're searching for? Let us assist you.

Enter your query below, and we'll provide instant results tailored to your needs.

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can send mail to admin@golinuxcloud.com

Thank You for your support!!

Leave a Comment

GoLinuxCloud Logo


We try to offer easy-to-follow guides and tips on various topics such as Linux, Cloud Computing, Programming Languages, Ethical Hacking and much more.

Programming Languages

JavaScript

Python

Golang

Node.js

Java

Laravel