How to Insert a value to a hidden input in Laravel Blade?


The blade is a template engine that helps you to build your view display in Laravel. It also helps you to use PHP code inside the template.

The blade templates are saved as filename.blade.php and are stored inside the resources/views/ folder.

To understand the above question let us create a view calling the blade template.

Inside routes/web.php I have created the following route that is calling the view hello with data ['mymsg' => 'Welcome to Tutorialspoint'].

Example 1

Let us see an example for this −

Route::get('hello', function () { return view('hello', ['mymsg' => 'Welcome to Tutorialspoint']); });

The hello.blade.php is inside the resources/views folder −

{{$mymsg}}

Output

The output when you test will be −

Welcome to Tutorialspoint

Example 2

Using input type="hidden"

Now let us add a hidden field inside the view created above. We can do it by using a hidden input field as shown below. In your hello.blade.php add the following:

<input type="hidden" value="{{$secretKey}}" name="key">

In your route pass the secretKey variable as shown below −

Route::get('hello', function () { return view('hello', ['mymsg' => 'Welcome to Tutorialspoint', 'secretKey'=>'123456']); });

Inside hello.blade.php you need to add the input field as shown below −

{{$mymsg}}
<input type="hidden" value="{{$secretKey}}" name="key">

Output

The output of the above code is as follows −

Welcome to Tutorialspoint

When you inspect the element you will see the input field as shown below −

Example 3

Let us make use of Form to display the input field as hidden in the blade template. The Form helps you with building HTML forms in Laravel.

Here is an example of how to use it. The hidden input field is added as follows −

<?php echo Form::hidden('secretkey', '878$54509'); ?>

The above is nothing but -

<input name="secretkey" type="hidden" value="878$54509">

hello.blade.php

{{$mymsg}} <?php echo Form::open(array('url'=>'/hello'));?> <?php echo Form::hidden('secretkey', '878$54509'); ?> <?php echo Form::close(); ?>

Output

The output of the above code is as follows −

Welcome to Tutorialspoint

When you inspect the page you will see it as follows −

Example 4

Adding more attributes to input field

To pass some more attributes to the input type="hidden" we can do it as follows −

{{$mymsg}} <?php echo Form::open(array('url'=>'/hello'));?> <?php echo Form::hidden('secretkey', '878$54509'); ?> <?php echo Form::hidden('secretkey', '878$54509', array('id' => 'key')) ?> <?php echo Form::close(); ?>

Output

The output of the above code is −

Welcome to Tutorialspoint

When you inspect the page you will see it as follows −

Updated on: 30-Aug-2022

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements