In laravel there are several ways to get data from the controller to view file .blade.php below is how to get data passed to the blade file
For example here is the controller file created and the corresponding ways involved
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
class EventController extends Controller
{
//method 1
public function index(Request $request)
{
$id = $request->query('id');
$posts= DB::table('posts')->where('id',$id)->get();
$pics = DB::table('pictures')->where('event_id',$id)->get();
// For passing multiple variable to view
return view('pages.eventPage',compact('posts','pics'));
}
//method 2
public function index2(Request $request)
{
$id = $request->query('id');
$post = DB::table('posts')->where('id',$id)->get();
//For passing single variable to view
return view('post', compact('post'));
}
//method 3
public function index3(Request $request)
{
$posts= DB::table('posts')->get();
// Passing data directly in view method
return view('post', ["posts" => $posts]);
}
//method 4
public function index4(Request $request)
{
$name = "Tony Stack";
//The with method allows you to pass just a single variable to a view
return view('post')->with('name', $name);;
}
}
In the view, parse the data using the @foreach blade syntax
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>User</title>
</head>
<body>
// method 1,2,3
<h1>User Page</h1>
@foreach ($post as $item )
{{ $item }}
@endforeach
// method 4
<h1>User Page</h1>
<p>{{ $name }}</p>
</body>
</html>
Good luck with the above methods
Leave a Reply