Different Ways Of Passing Data From Controller To View In Laravel

In this quick example, I will explain how to pass data from controller to view in laravel 9 application. If you do not know how to pass array data from controller to view in laravel then this example is for you. You will learn from this example pass data to view laravel.

Laravel provides a very convenient way to pass data from the controller to the blade file. I will show you the following three ways to pass data from controller to view. We can pass data to view in laravel in many ways like using compact, array or using with helper method.

 

Example 1: Using Compact()

See the first example using the compact() method:

app/Http/Controllers/DemoController.php

namespace App\Http\Controllers;
  
use Illuminate\Http\Request;
  
class DemoController extends Controller
{
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function index(Request $request)
    {
        $title = "Welcome to codecheef.org";
        $subTitle = "Thank you";
  
        return view('demo', compact('title', 'subTitle'));
    }
}

 

And print them like:

resources/views/demo.blade.php

{{ $title }}
{{ $subTitle }}

 

Example 2: Using Array

See the first example using the array() method:

app/Http/Controllers/DemoController.php

namespace App\Http\Controllers;
  
use Illuminate\Http\Request;
  
class DemoController extends Controller
{
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function index(Request $request)
    {
        $title = "Welcome to codecheef.org";
        $subTitle = "Thank you";
  
        return view('demo', [
            'title' => $title,
            'subTitle' => $subTitle,
        ]);
    }
}

 

Example 3: Using With()

And the last one using with() method:

app/Http/Controllers/DemoController.php

namespace App\Http\Controllers;
  
use Illuminate\Http\Request;
  
class DemoController extends Controller
{
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function index(Request $request)
    {
        $title = "Welcome to codecheef.org";
        $subTitle = "Thank you";
  
        return view('demo')
                    ->with('title', $title)
                    ->with('subTitle', $subTitle);
    }
}

 

Read also: How to Pass Multiple Parameters in Laravel Route?

 

Hope it can help you.

 

#laravel