How to pass controller data to view in laravel?

by elise_daugherty , in category: PHP Frameworks , 5 months ago

How to pass controller data to view in laravel?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by orpha , 5 months ago

@elise_daugherty 

To pass controller data to a view in Laravel, you can use the with() method on the view() function. Here's a step-by-step guide on how to pass data from a controller to a view:

  1. In your controller method, retrieve the data that you want to pass to the view. For example, you may have a controller method like this:
1
2
3
4
5
6
7
8
9
public function index()
{
    $data = [
        'title' => 'Welcome to our blog',
        'posts' => Post::all()
    ];

    return view('pages.home', $data);
}


  1. In this example, the controller method is passing an array of data containing a title and a collection of posts to the home.blade.php view. The with() method is used to pass the data to the view.
  2. In the corresponding view file (resources/views/pages/home.blade.php), you can access the passed data using Blade syntax. For example, you can display the title and posts like this:
1
2
3
4
5
6
7
8
<h1>{{ $title }}</h1>

@foreach($posts as $post)
    <div>
        <h2>{{ $post->title }}</h2>
        <p>{{ $post->content }}</p>
    </div>
@endforeach


  1. When you navigate to the route associated with the controller method, the data passed from the controller will be available in the view, and you can use it to customize the content displayed on the page.


By following these steps, you can easily pass controller data to a view in Laravel and display it on your web page.