Reputation: 185
I want to fetch data from database table named 'users' and display the output in a table.
I have written below code but it's not working.
I am using Laravel 5.5
@extends('layouts.app')
@section('content')
<div class="container">
<h2>Admin Panel</h2>
<p>Data of the Registered Users.</p>
<table class="table table-bordered">
<thead>
<tr>
<th>Id</th>
<th>Name</th>
<th>Email</th>
</tr>
</thead>
<tbody>
$users = DB::table('users')->select('id','name','email')->get();
@foreach($users as $value)
<tr>
<td>{{ $value->id }}</td>
<td>{{ $value->name }}</td>
<td>{{ $value->email }}</td>
</tr>
@endforeach
</tbody>
</table>
</div>
@endsection
Error: Undefined Variable: users
Upvotes: 2
Views: 94016
Reputation: 11
You Are using php in blade file first make controller for controller run a command in terminal php artisan make:controller usercontroller
then write this:
class usercontroller extends Controller
{
public function index()
{
$users = DB::table('users')->select('id','name','email')->get();
$data = compact('users')
return view('your-view-name')->with('$data');
}
}
Upvotes: 0
Reputation: 3962
The problem is that you're trying to mix PHP within your (Blade) template. Although it is possible to do so with @php
directives, this is bad practice: your view should not contain any business logic.
Ideally you want to pass this data from your controller. It should look something like this:
use Illuminate\Support\Facades\DB;
class UserController extends Controller
{
public function index()
{
$users = DB::table('users')->select('id','name','email')->get();
return view('some-view')->with('users', $users);
}
}
Read more on passing data to views here.
Upvotes: 8
Reputation: 3543
You are doing it all wrong, the point of MVC
design is to have your controllers
do the application logic, your views to represent a representation of that data
and models to contain the data you need
, in your case you are missing the point completely by using DB::table
inside of your view, so here is an example code which you might need to correct a bit:
The example below doesn't show MVC
pattern since the data
is passed from inside a closure of a route
web.php
Route::get('/', function () {
$users = DB::table('users')->select('id','name','email')->get();
return view('VIEW-NAME-HERE', compact('users'));
});
view.blade.php
@foreach($users as $user)
{{ $user->id }} {{ $user->name }} {{ $user->email }}
@endforeach
Change VIEW-NAME-HERE
with the name of your view
file, for example index
or users.index
Upvotes: 4