I am using Laravel 5.4 and I want to view my data in database from my view page (listpetani.blade.php).
Here is the code of my project:
HTML:
<div class="table-responsive">
<table class="table table-striped table-hover table-condensed">
<thead>
<tr>
<th><strong>No</strong></th>
<th><strong>Nama Petani</strong></th>
<th><strong>Alamat</strong></th>
<th><strong>No. Handphone</strong></th>
<th><strong>Lokasi</strong></th>
</tr>
</thead>
<tbody>
<tr>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
</tr>
</tbody>
</table>
</div>
PHP:
In my listpetani.blade.php I have an empty table and I want to show data from database tbl_user:
Route::get('listpetani', function () {
$petani = DB::table('tbl_user')->pluck('id_user', 'username', 'alamat', 'no_telp', 'id_lokasi');
return view('listpetani', ['petani' => $petani]);
});
And the table in my page: view in browser
I want to show all the data from database into my view in laravel 5.4. Can anybody help me?
[SOLVE]
Thank you guys, I already solve this problem
This is the solved code
web.php (routes)
Route::get('listpetani', function () {
$petani = DB::table('tbl_user')->get();
return view('listpetani', ['petani' => $petani]);
});
and in my listpetani.blade.php
#foreach($petani as $key => $data)
<tr>
<th>{{$data->id_user}}</th>
<th>{{$data->nama_user}}</th>
<th>{{$data->alamat}}</th>
<th>{{$data->no_telp}}</th>
<th>{{$data->id_lokasi}}</th>
</tr>
#endforeach
You can get data from database in view also
#php( $contacts = \App\Contact::all() )
#php( $owners = \App\User::all())
<select class="form-control" name="owner_name" id="owner_name">
#foreach($contacts as $contact)
<option value="{{ $contact->contact_owner_id }}">{{ $contact->contact_owner }}</option>
#endforeach
</select>
It would be better if you pass data from controller to view.
return view('greetings', ['name' => 'Victoria']);
Checkout the docs:
https://laravel.com/docs/8.x/views#passing-data-to-views
Alternatively you can use #forelse loop inside laravel blade
#forelse($name as $data)
<tr>
<th>{{ $data->id}}</th>
<th>{{ $data->name}}</th>
<th>{{ $data->age}}</th>
<th>{{ $data->address}}</th>
</tr>
#empty
<tr><td colspan="4">No record found</td></tr>
#endforelse
In your controller:
$select = DB::select('select * from student');
return view ('index')->with('name',$select);
In Your view:
#foreach($name as $data)
<tr>
<th>{{ $data->id}}</th> <br>
<th>{{ $data->name}}</th> <br>
<th>{{ $data->age}}</th> <br>
<th>{{ $data->address}}</th>
</tr>
#endforeach
I hope this can help you.
#foreach($petani as $p)
<tr>
<td>{{ $p['id_user'] }}</td>
<td>{{ $p['username'] }}</td>
<td>{{ $p['alamat'] }}</td>
<td>{{ $p['no_telp'] }}</td>
<td>{{ $p['id_lokasi'] }}</td>
</tr>
#endforeach
**In side controller you pass this **:
$petanidetail = DB::table('tb1_user')->get()->toArray();
return view('listpetani', compact('petanidetail'));
and Inside view you use petanidetail variable as follow:
foreach($petanidetail as $data)
{
echo $data;
}
I hope you already know this, but try use Model and Controller as well,
Let the route take the request, and pass it to controller
and use Eloquent so your code can be this short:
$petani = PetaniModel::all();
return view('listpetani', compact('petani));
and instead using foreach, use forelse with #empty statement incase your 'listpetani' is empty and give some information to the view like 'The List is Empty'.
Try this:
$petani = DB::table('tbl_user')->pluck('id_user', 'username', 'alamat', 'no_telp', 'id_lokasi');
return view('listpetani', ['petani' => $petani]);
on your view iterate $petani using foreach() like:
foreach($petani as $data)
{
echo $data->id_user; // $petani is a Std Class Object here
echo $data->username;
}
Other answers are correct, I just want to add one more thing, if your database field has html tags then system will print html tags like < p > for paragraph tag. To remove this issue you can use below solution:
You may need to apply html_entity_decode to your data.
This works fine for Laravel 4
{{html_entity_decode($post->body)}}
For Laravel 5 you may need to use this instead
{!!html_entity_decode($post->body)!!}
Related
In index.blade.php, I wrote these codes to show users who have roles
<thead>
<tr>
<th scope="col">Name</th>
<th scope="col">Email</th>
<th scope="col">Roles</th>
<th scope="col">Actions</th>
</tr>
</thead>
<tbody>
#foreach($users as $user)
<tr>
<td>{{ $user->name }}</td>
<td>{{ $user->email }}</td>
<td>{{ $user->roles }}</td>
<td>Show</td>
</tr>
#endforeach
</tbody>
And I wrote these codes in UserController,
$userId = \DB::table('role_user')->get()->pluck('user_id');
$users = User::find($userId);
return view('admin.index', compact('users'));
And I got these in the website:
[{"id":1,"name":"User Administrator","description":null,"created_at":"2021-11-23 03:06:49","updated_at":"2021-11-23 03:06:49","pivot":{"user_id":1,"role_id":1}}]
[{"id":2,"name":"Moderator","description":null,"created_at":"2021-11-23 03:06:49","updated_at":"2021-11-23 03:06:49","pivot":{"user_id":2,"role_id":2}}]
How can I only display the names in the table role column?
When calling user->roles, you're most likely calling towards a relation on your User model. This means that you're returning a collection. If you place a collection in curly braces in blade ({{ $user->roles }}), Laravel automatically calls toArray() on each model, and a json_encode on the result, which results in the JSON strings you end up seeing.
You only want the names, however, so it'd be better to grab those values and convert them to a string. An option of doing so is by plucking the name, and imploding the result:
implode(', ', $user->roles()->pluck('name')->toArray());
You have to call toArray() on the pluck() result, else you'll have a collection instead of an array, which implode does not work with.
If the user is logged in and his role is to be displayed, you can use this in your blade:
{{ Auth::user()->roles->pluck('name') }}
Or you would like to display the rools of another user, then you can do it as follows:
// in Controller fetch the user:
$user = User::find(42);
// in your Blade:
{{ $user->roles->pluck('name') }}
In this context, you have a number of methods that you can use:
roles
hasRole
hasAnyRole
hasAllRoles
getRoleNames
I'm trying to make a show view with Laravel 8 but i can't show the detail, this is the code from the controller:
public function show($id)
{
$accesorios=DB::table('accesorio as acc')
->join('detalle_aparato as da','acc.idAccesorio','=','da.idAccesorio')
->select('acc.Nombre')
->where('da.idAparato','=',$id);
return view("almacen.aparato.show",["accesorio"=>Accesorio::findOrFail($id)]);
}
And this is the code from the view:
#foreach ($accesorio as $acc)
<tr>
<td>{{ $acc->Nombre}}</td>
</tr>
#endforeach
Error message
When I use:
#foreach ($accesorio as $acc)
<tr>
<td>{{ $acc}}</td>
</tr>
#endforeach
It prints: 1 for each record
Hope you can help me
In you're controller you're using DB::Table to set the $accesorios variable, but never using it.
You then are setting accesorio in your view to Accesorio::findOrFail($id) which will only return one instance of the object.
Either pass $accessorios into your view
return view("almacen.aparato.show",["accesorios"=>$accessorios]);
then loop through it
#foreach ($accesorios as $acc)
<tr>
<td>{{ $acc->Nombre}}</td>
</tr>
#endforeach
or since you're just sending one instance of the object to the view, remove the loop and you can render it like this.
<tr>
<td>{{ $accesorio->Nombre }}</td>
</tr>
i cant access my admin_table i know i have and problem on my route on the admin_table please help me on my route Property [id] does not exist on this collection instance.
my admin_table.blade
#foreach ($users as $positions)
#foreach ($positions->admins as $position )
<tbody>
<tr>
<td>{{ $position->id}}</td>
<td>{{ $position->first_name}}</td>
<td>{{ $position->last_name}}</td>
<td>{{ $position->contact}}</td>
<td>{{ $position->departments->department}}</td>
<td>{{ $position->schoolpositions->school_position}}</td>
<td>{{ $position->email}}</td>
<th> Edit
</th>
</tr>
</tbody>
#endforeach
</tr>
</tbody>
#endforeach
#endforeach
</table>
this is my route
Route::get('/admin_table', 'DashboardController#index');
Route::put('/admin_table/{id}', 'DashboardController#store');
Route::get('/admin_table', 'DashboardController#show');
Route::get('/teacher_editform/{id}', 'DashboardController#edit');
Route::put('/teacher_editform/{id}', 'DashboardController#update')->name('teacheradminpage.teacher_tableform.teacher_editform');
this is my controller
public function edit($id)
{
$departments = Department::find($id);
$users = Schoolposition::find($id);
$students = Student::find($id);
$admins = Admin::find($id);
return view('teacheradminpage.teacher_tableform.teacher_editform', compact('departments','users','students','admins', 'id', 'id', 'id', 'id'));
}
Your issue is that you put an extra $position before the array. Your route should be
Edit
You've got several issues in this code that probably need attention. The main issue with the position error, seems to be that you've got a circular path to get that $position in your anchor tab within the loop.
This section is likely not creating what you want:
#foreach ($users as $positions)
#foreach ($positions->admins as $position )
This is roughly saying - take my collection of users and make a new collection of positions that are directly attached to each user object. From here, take that collection of positions and try and find a collection of admins on that are attached to that collection and then find a $position. (I think this is close to what it is trying to do...)
When you get to the inside of the loop and your anchor / route, you are asking the anchor to find an id on something that is likely either non-existent, or a collection again.
You have already passed in admins to this view. It would make sense to use that as your top level loop item, no?
To fix, use admins as the only loop item:
#foreach ($admins as $position )
Edit Your Blade With
#foreach ($users as $positions)
#if(!empty($positions->admins)
#foreach ($positions->admins as $position )
<tbody>
<tr>
<td>{{ $position->id}}</td>
<td>{{ $position->first_name}}</td>
<td>{{ $position->last_name}}</td>
<td>{{ $position->contact}}</td>
<td>{{ $position->departments->department}}</td>
<td>{{ $position->schoolpositions->school_position}}</td>
<td>{{ $position->email}}</td>
<th> Edit
</th>
</tr>
</tbody>
#endforeach
</tr>
</tbody>
#endforeach
#endif
#endforeach
</table>
I'm an absolute beginner and I'm trying to do a CRUD in Laravel, but I can not figure it out why my variables aren't being passed over to the view so I can have a dynamic display of them in the table.
My "routes" work fine.
Then my controller
public function getHome()
{
$results = Crud::index();
return view('pages/home', ['results' => $results]);
}
Calls my "Crud" model
class Crud extends Model
{
public static function index()
{
return $results = DB::table('data')
->whereNotNull('id')
->get();
}
}
And goes to my view as seen in the controller
#extends('main')
#section('title', '| Home')
#section('content')
<div class="container">
#include ('partials/_jumbotron')
<table class="table table-inverse">
<thead>
<tr>
<th>#</th>
<th>First Name</th>
<th>Last Name</th>
<th>Username</th>
</tr>
</thead>
<tbody>
#if(!empty($results))
#foreach($results as $result)
<tr>
<td scope="row">$result->$id</th>
<td>$result->$first_name</td>
<td>$result->$last_name</td>
<td>$result->$username</td>
</tr>
#endforeach
#endif
</tbody>
</table>
</div>
#endsection
Thanks for the help in advance...I'm losing my mind
And sorry If I wasn't specific enough..
Edit1: I did as you say, but I'm still not outputing data to my table? Is there anything else wrong in the stated code or is the bug somewhere deeper?
Edit2: Thanks everyone for the pointed out mistakes - blade {{ }} and object properties
$object->propertie not $object->$propertie
When I fixed those mistakes which were obviously denying the output I remembered that I have an empty database.. Case Closed - Thanks everyone for the help
You're not printing the variables. You're printing literals.
If you want to print the variables (echo them) in blade files, you need to wrap them in curly brackets. Also there's not $ when you want to display an object attribute. Like that:
#foreach($results as $result)
<tr>
<td scope="row">{{ $result->id }}</th>
<td>{{ $result->first_name }}</td>
<td>{{ $result->last_name }}</td>
<td>{{ $result->username }}</td>
</tr>
#endforeach
I am a beginner too, I thought maybe you might want to try this as well
public function getHome()
{
$results = Crud::index();
return view('pages/home', compact('results'));
}
But before anything else make sure if your code is actually returning your data from DB using
dd($results)
The first of all cleaner will be using laravel with function for example
return view('pages/home')->with('results', $results);
Next you try to get $result->$first_name it didint working becouse first_name is not variable, laravel return object so you can get first_name like that:
{{$result->first_name}}
In laravel 5.2 I have a paginated table of a model.
#CityController
public function index(Request $request){
$cities = City::orderBy('name');
return view('pages.city.index', ["cities" => $cities ->paginate(25)]);
}
This works fine, but when I try to sort the results inside the blade view does not work.
#index.blade.php
<table>
<thead>
<tr class="sui-columnheader">
<th class="sui-headercell" data-field="Id">
Id
</th>
</thead>
<tbody class="list">
#foreach ($cities as $city)
<tr class="sui-row">
<td class="sui-cell id">{!! $city->id !!}</td>
</tr>
</tbody>
</table>
When I click the sort button just reloads the page but no sort is applied.
Is because of the "orderBy" clause?
How can I make it work and defaults to order by name?
Am I missing something?
Something like this perhaps. You would want to make sure you limit what can be passed to that orderBy. A URL like "...something?sort=blah" would cause orderBy('blah'), which your table doesn't have, which will cause a DB error.
public function index(Request $request)
{
$cities = City::orderBy($request->input('sort', 'name'))->paginate(25);
return view('pages.city.index', ['cities' => $cities]);
}
{{ $cities->appends(Request::query())->render() }}
Just giving you a functional example, though you will have to adjust based on your own rules.
The appends is just allowing you to continue to paginate based on the current sorting, by passing the sort option via the query string of the pagination links.
Update:
Using your example where there is a default, but imagining there can be more than just 1 other field to sort by:
$sort = trim($request->input('sort'));
// if it is in the acceptable array use it, otherwise default to 'name'
$sort = in_array($sort, ['id', ...]) ? $sort : 'name';
$cities = City::orderBy($sort)->paginate(25);
<table>
<tr>
<th>ID</th>
<th>NAME</th>
...
</tr>
#foreach ($cities as $city)
<tr>
<td>{{ $city->id }}</td>
<td>{{ $city->name }}</td>
...
</tr>
#endforeach
...
{{ $cities->appends(Request::query())->render() }}
Just an example, you can do this how you would like.