How to send Data from the Controller to View in Laravel?
In this tutorial, we will learn How to send Data from the Controller to View in Laravel? I would like to show you how to pass data from the controller to view in the Laravel application. We will use how to pass multiple data from the controller to view in the Laravel application. Here, We are creating a basic example of how to send variable values from the controller to view in Laravel. And you can use this example with Laravel 6, Laravel 7, Laravel 8, and Laravel 9 versions. I will give you three ways to pass data from the controller to view.
How to send Data from the Controller to View in Laravel?
<?php #app/Http/Controllers/HomeController.php namespace App\Http\Controllers; use Illuminate\Http\Request; class HomeController extends Controller { /** * Write code on Method * * @return response() */ public function index(Request $request) { $page_title = "Users"; $redirect_route = "users.index"; $users = User::where('role', 1)->get(); // Using Compact() return view('users.index', compact('users', 'page_title', 'redirect_route')); // Using With() return view('users.index') ->with('users', $users) ->with('page_title', $page_title) ->with('redirect_route', $redirect_route); //Using Array return view('users.index', [ 'users' => $users, 'page_title' => $page_title, 'redirect_route' => $redirect_route ]); } }
resources/views/users/index.blade.php
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8'>
<meta http-equiv='X-UA-Compatible' content='IE=edge'>
<title>How to send Data from the Controller to View in Laravel?</title>
<meta name='viewport' content='width=device-width, initial-scale=1'>
</head>
<body>
<div class="main_content_iner">
<h1>{{ $page_title }}</h1>
<div class="container-fluid p-0">
<div class="row justify-content-center">
<div class="col-lg-12">
<table id="userTable" class="table" style="width:100%">
<thead>
<tr>
<th scope="col">Name</th>
<th scope="col">Email</th>
<th scope="col">Company</th>
<th scope="col" data-orderable="false">Action</th>
</tr>
</thead>
<tbody>
@forelse($users as $key=>$value)
<tr>
<td>{{ $value->contact_name }}</td>
<td>{{ $value->email }}</td>
<td>{{ $value->company }}</td>
<td>
<a class="btn btn-sm btn-default float-start" href="{{ route($redirect_route.'.edit', $value->id) }}"><i class="ti-pencil" aria-hidden="true"></i></a>
<form action="{{route($redirect_route.'.destroy', $value->id)}}" method="POST" class="d-flex">
@method('DELETE')
@csrf
<button class="btn btn-sm btn-default" onclick="return confirm('Do you really want to delete?')" type="submit"> <i class="ti-trash" aria-hidden="true"></i></button>
</form>
</td>
</tr>
@empty
<tr><td>No data found!</td></tr>
@endforelse
</tbody>
</table>
</div>
</div>
</div>
</div>
</body>
</html>