Laravel - paginated model sort link in blade view - php

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.

Related

Laravel 6 in index blade how can I show only users who have roles and their roles in the table

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

Attempt to read property "Nombre" on bool

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>

How to solve the problem of dynamic rowspan problem in table in laravel

I am trying to show the table like below image
And i write the logic for this table creation is below
#foreach($users as $key => $user)
<tr>
<td>{{$key+1}}</td>
<td>{{$user->name}}</td>
<td rowspan="{{count($users->where('area',$user->area))}}">
{{$user->userarea->name}}</td>
<td rowspan="{{count($user->candidate->election->candidates)}}">{{$user->candidate->election->name}}</td>
</tr>
#endforeach
</tbody>
But this code produce me the following code like this
Here The Election and Candidate has one to many relationships and candidate and user has one one to one relationshipHelp me achieve my expected results.
You could keep track of which elections/area's have been rendered already. This could be done by creating an array containing a reference to these objects. Then in the template just add an if statement checking whether an election/area has been rendered:
<?php $renderedElections = []; ?>
<?php $renderedAreas = []; ?>
#foreach($users as $key => $user)
<tr>
<td>{{$key+1}}</td>
<td>{{$user->name}}</td>
#if (!in_array($user->userarea->name, $renderedAreas))
<?php $renderedElections[] = $user->userarea->name ?>
<td rowspan="{{count($user->userarea->name)}}">
{{$user->userarea->name}}
</td>
#endif
#if (!in_array($user->candidate->election->name, $renderedElections))
<?php $renderedElections[] = $user->candidate->election->name ?>
<td rowspan="{{count($user->candidate->election->candidates)}}">
{{$user->candidate->election->name}}
</td>
#endif
</tr>
This is not the best solution, but its simple and easy. For this to work, the users must be sorted perfectly by election and area.
This code is untested but should theorethically work. I tryied to gather informations about your model relationships from the code you posted, but it might need some tweaking with the model names and relations.
The following code basically fetches all the users each with their area, candidate and candidate.election relationships, then group users by 'election name' (first criteria), then 'area name' (second criteria).
The resulting array will be something like this:
// $elections will be:
// [
// 'Presidential' => [
// 'Dhaka-5' => [ candidates for that area in that election type ],
// 'Dhaka-1' => [ candidates for that area in that election type ],
// ...
// ],
// ...
// ]
In your controller do:
$elections = User::with('area', 'candidate.election')->get()->groupBy(function ($user) {
return $user->candidate->election->name;
}, function ($user) {
return $user->area->name;
});
// then pass $elections to the view...
Then in your view:
<table>
#php ($i = 1)
#foreach ($elections as $election => $areas)
#foreach ($areas as $area => $candidates)
#php ($areaLoop = $loop)
#foreach ($candidates as $user)
<tr>
<td>{{ $i++ }}</td>
<td>{{ $user->name }}</td>
#if ($loop->first)
<td rowspan="{{ $candidates->count() }}">{{ $area }}</td>
#endif
#if ($areaLoop->first)
<td rowspan="{{ $areas->sum(function ($area) { return $area->count(); }); }}">{{ $election }}</td>
#endif
</tr>
#endforeach
#endforeach
#endforeach
</table>
Note that $candidates->count() will be the number of candidates for that particular election area of the current election type. $areas->sum(...) will sum the number of candidates for each area to get the total count of candidates in that election type.
If you need further explaination or something doesn't work, just let me know. All the documentation about the collection functions I used is available here.

Laravel Variable Not Passing Through

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}}

How to get data from database to view page in laravel?

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)!!}

Categories