How To Pass Data To Views In laravel With Examples

admin_img Posted By Bajarangi soft , Posted On 17-09-2020

MVC framework, MVC means Model View and Controller the letter “V” stands for Views. It separates the application logic and the presentation logic. Views are stored in resources/views directory and view files contains the HTML which will be served by the application and inside views files should save with extension of blade.php(demo.blade.php)

How To Pass Data To Views In laravel With Examples

Passing Data To Views

As you saw in the previous examples, you may pass an array of data to views:

return view('greetings', ['name' => 'Victoria']);
 

When passing information in this manner, the data should be an array with key / value pairs. Inside your view, you can then access each value using its corresponding key, such as <?php echo $key; ?>. As an alternative to passing a complete array of data to the view helper function, you may use the with method to add individual pieces of data to the view:
 

return view('greeting')->with('name', 'Victoria');


Sharing Data With All Views

Occasionally, you may need to share a piece of data with all views that are rendered by your application. You may do so using the view facade's share method. Typically, you should place calls to share within a service provider's boot method. You are free to add them to the AppServiceProvider or generate a separate service provider to house them:

<?php

namespace App\Providers;

use Illuminate\Support\Facades\View;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        //
    }

    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        View::share('key', 'value');
    }
}


Example(1)

1 − Create demo.blade.php file and open resources/views/demo.blade.php to implement code as below

resources/views/demo.blade.php

<!DOCTYPE html>
<html>
<head>
    <title>Example For Creating Views In Laravel </title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
</head>
<body>
<h1>To Know More About Laravel Visit Our {{$name}} Site</h1>
</body>
</html>


 2 − Create route in app/Http/routes.php file to set the route for the above view.

app/Http/routes.php

Route::get('/demo', function() {
    return view('demo',['name'=>'Bajarangisoft']);
});

 
3
 − The value of the key name will be passed to demo.blade.php file and $name will be replaced by that value.

4 − To check output pass below url in google chrome

http://localhost/laraveldemoproject/public/demo

Related Post