Trying to use laravel pagination breaks my controller/view - pagination

I'm trying to get Pagination working in Laravel. I've not used pagination before so am trying to use some examples from the docs and google results. I'm wondering if I need to turn 'pagination' on somewhere in config.
Here's my simple working controller:
public function get_index() {
$locations = Location::all();
return View::make('location.index')->with('locations', $locations)->render();
}
When I try and add pagination like this it breaks:
public function get_index() {
$locations = Location::paginate(5);
return View::make('location.index')->with('locations', $locations)->render();
}
..and I get the error:
Unhandled Exception
Message:
Error rendering view: [location.index]
Trying to get property of non-object
Here's my location.index view:
#layout('layouts.blank')
#section('content')
<div class="row">
<div class="twelve columns">
<div role="main" id="content">
<h3>Locations - All</h3>
#if($locations)
<table class="twelve">
<thead>
<tr>
<th style="text-align: left;">Address</th>
<th>Area</th>
<th>Region</th>
<th>Edit</th>
<th>Delete</th>
</tr>
</thead>
#foreach($locations as $location)
<tbody>
<tr>
<td style="text-align: left;">{{ $location->company,', ',$location->add_name,', ',$location->add_city }}</td>
<td> – </td>
<td> – </td>
<td>{{ HTML::link('location/update/'.$location->id, '',array('class'=>"foundicon-edit updateicon")) }}</td>
<td>{{ HTML::link('location/delete/'.$location->id, '',array('class'=>"foundicon-remove warnicon")) }}</td>
</tr>
</tbody>
#endforeach
</table>
#else
Looks like we haven't added any locations, yet!
#endif
<p>{{ HTML::link('location/create', 'Create a location', array('class'=>"small radius button")) }}</p>
</div>
</div>
</div>
#endsection

I hadn't read deeply enough into the subject. It's now working and here's what I had to change in the view:
//from:
#foreach($locations as $location)
//to:
#foreach($locations->results as $location)
That returned just 5 results. Then to add links to the footer of my table I added this HTML/Blade:
<tfoot>
<tr>
<td colspan="5"> {{ $locations->links() }} </td>
</tr>
</tfoot>
Hope someone else benefits as I didn't find this terribly clear in the docs.

Related

Laravel 9 Livewire Pagination is not working at all

In my project(s) I want to make use of Livewire Pagination. I have setup everything according to the Livewire Docs. I make use of components to view everything.
I tried the same as you can find in the following code in my real projects, but nothing works.
Here is my code of a test setup (and also here nothing works):
Model User
<?php
namespace App\Models;
use App\Casts\UserRoleCast;
use App\Constants\UserRole;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Fortify\TwoFactorAuthenticatable;
use Laravel\Jetstream\HasProfilePhoto;
use Laravel\Sanctum\HasApiTokens;
use Livewire\WithPagination;
class User extends Authenticatable
{
use HasApiTokens;
use HasFactory;
use HasProfilePhoto;
use Notifiable;
use TwoFactorAuthenticatable;
use WithPagination;
/**
* The attributes that are mass assignable.
*
* #var string[]
*/
protected $fillable = [ ....etc.....
UserPagination.php
<?php
namespace App\Http\Livewire;
use Livewire\Component;
use App\Models\User;
use Livewire\WithPagination;
class UserPagination extends Component
{
use WithPagination;
public function render()
{
return view('livewire.user-pagination', [
'users' => User::paginate(5)
])->layout('layouts.guest');
}
}
Blade view
<div>
<table class="table min-w-full mb-4">
<thead>
<tr class="border-b-2 border-gray-300">
<th class="px-6 py-3 text-left text-sm leading-4 tracking-wider">ID</th>
<th class="px-6 py-3 text-left text-sm leading-4 tracking-wider">Naam</th>
<th class="px-6 py-3 text-left text-sm leading-4 tracking-wider">Email</th>
<th class="px-6 py-3 text-left text-sm leading-4 tracking-wider">Password</th>
</tr>
</thead>
<tbody>
#forelse($users as $user)
{{-- <tr class="border-b border-gray-500" wire:key="user-{{ $user->id }}"> --}}
<tr class="border-b border-gray-500">
<td class="px-6 py-4 whitespace-no-wrap text-sm leading-5">
{{ $user->id }}
</td>
<td class="px-6 py-4 whitespace-no-wrap text-sm leading-5">
{{ $user->name }}
</td>
<td class="px-6 py-4 whitespace-no-wrap text-sm leading-5">
{{ $user->email }}
</td>
<td class="px-6 py-4 whitespace-no-wrap text-sm leading-5">
{{ $user->password }}
</td>
</tr>
#empty
<tr>
<td colspan="6" class="px-6 py-4 whitespace-no-wrap text-sm leading-5">Geen sponsors gevonden</td>
</tr>
#endforelse
</tbody>
</table>
{{ $users->links() }}
</div>
composer.json
"laravel/framework": "^9.19",
"laravel/jetstream": "^2.13",
"laravel/sanctum": "^3.0",
"laravel/tinker": "^2.7",
"livewire/livewire": "^2.5",
Furthermore
I have my #livewireStyles and my #livewireScripts at the right place. I know it's right, because the rest of the application is working.
But clicking on the links doesn't do anything. Nothing changes in de URI and nothing happens on screen.
What is wrong here? Why doesn't it working?
I tried everything according to the Livewire Docs and 'solutions' I found online.
SOLVED
I made a mistake by adding a use statement in the models, the use statement:
use WithPaginator
This is a Livewire trait and only for livewire components.
I removed the use statement and everything worked.
Another problem is when I load for example all Users with pagination in the mount method of a component I get an error. Solution here was to load all Users in de render method.

How to get values dynamically from a collection in a model in Razor Pages?

I'm trying to render lists of elements dynamically in ASPNETCore Razor Pages but I can't find the way to show the values of properties using Display Helper. M
<table class="table datatable">
<thead>
<tr>
#foreach (var item in Model.GetFieldNamesForList())
{
<th>
#Html.DisplayName(item)
</th>
}
<th></th>
</tr>
</thead>
<tbody>
#foreach (var item in Model.School) {
<tr>
#foreach (var propertyName in Model.GetFieldNamesForList())
{
<td>
// How to use #Html.Display using item from Model.School and the propertyName
</td>
}
<td>
<a asp-page="./Edit" asp-route-id="#item.Id" class="btn btn-primary btn-sm"><i class="material-icons md-16">edit</i></a>
<a asp-page="./Details" asp-route-id="#item.Id" class="btn btn-primary btn-sm"><i class="material-icons md-16">visibility</i></a>
<button action="submit" asp-page-handler="Delete" asp-route-id="#item.Id" class="btn btn-danger btn-sm"><i class="material-icons md-16">delete</i></button>
</td>
</tr>
}
</tbody>
</table>
In the meantime, I use reflection directly, but I would prefer use the Display method from helpers.
#item.GetType().GetProperty(propertyName).GetValue(item, null)

The DELETE method is not supported for this route. Supported methods: GET, HEAD, POST. when deleting first item

I'm a beginner in Laravel 7. I am trying to create a checkout form when purchasing items. The problem is whenever I try to delete the first item the 'The DELETE method is not supported for this route. Supported methods: GET, HEAD, POST.' shows up. However, I am able to delete the following items under it that I put into the checkout form.
This is my CheckoutController
public function destroy($id)
{
Temp_order::where('id',$id)->delete();
return redirect('checkout')->with('success','Product deleted successfully');
}
And this is the code for the table
<tbody>
#forelse ($order as $item)
<tr>
<td id="item_code">{{ $item->item_code }}</td>
<td class="cart_product_img" id="image">
<img src="" alt="Unavailable" style="width: 70px; height:70px"></img>
</td>
<td id="item_name">
{{ $item->item_name }}
</td>
<td id="price">
₱ {{ number_format($item->price, 2) }}
</td>
<td class="qty" id="qty">
<div class="qty-btn d-flex">
<div class="quantity">
<input type="number" class="qty-text" id="qty" step="1" min="1" max="300" name="quantity" value="{{ $item->quantity }}">
</div>
</div>
</td>
<td id="subtotal">
₱ {{ number_format($item->subtotal, 2) }}
</td>
<td>
<form action="{{ route('checkout.destroy', $item->id) }}" method="post">
#csrf
#method('DELETE')
<button type="submit" class="btn btn-danger btn-sm">Remove</button>
</form>
</td>
</tr>
#empty
<tr>
<td>
<p> NO ITEMS IN CART </p>
</td>
</tr>
#endforelse
</tbody>
And this is my route
Route::get('/', function () {
return view('auth.login');
});
Auth::routes();
Route::get('/home', 'HomeController#index')->name('home');
Route::resource('ordering', 'OrderingController')->middleware('auth');
Route::resource('inventory', 'InventoryController')->middleware('auth');
Route::resource('checkout', 'CheckoutController')->middleware('auth');
Can you help me masters?
Try to update CheckoutController
public function destroy(Temp_order $item)
{
$item->delete();
return redirect('checkout')->with('success','Product deleted successfully');
}

How to display my search to my table in VueJs?

I just want to ask, I want to display the searched value in my table?
Below code displays Memb_ID in div.
div>
<div class="search-wrapper">
<input type="text" v-model="search" placeholder="Search title..">
<label>Search title:</label>
</div>
<div v-for="cust in filteredList" :key="cust.id">{{ cust.Memb_ID }}</div>
<div class="myTable table-responsive">
<table class="table">
<thead class="thead-dark">
<tr>
<th>Member ID</th>
<th>First Name</th>
<th>Middle Name</th>
<th>Last Name</th>
<th>Address</th>
<!-- <th>URL</th> -->
</tr>
</thead>
<tbody>
<tr v-for="result in results" :key="result.id">
<td>{{result.Memb_ID}}</td>
<th>{{result.First_Name}}</th>
<th>{{result.Middle_Name}}</th>
<th>{{result.Last_Name}}</th>
<th>{{result.Address}}</th>
<!-- <th>{{user.url}}</th> -->
</tr>
</tbody>
</table>
</div>
This is the output of my code.
I want something like this
I got the code from this question but couldn't implement on my own. Thanks for help!
So I thought I solved my problem by looping in the table body.
There's a bug in here. Every time I reload the page it doesn't load the vue file lol. I thought it was okay after refreshing the page it didn't display the table.
I don't know the bug
<div>
<input type="text" v-model="search" placeholder="Search title..">
</div>
<div class="myTable table-responsive">
<table class="table">
<thead class="thead-dark">
<tr>
<th>Member ID</th>
<th>First Name</th>
<th>Middle Name</th>
<th>Last Name</th>
<th>Address</th>
</tr>
</thead>
<tbody>
<tr v-for="result in filteredList" :key="result.id">
<td>{{result.Memb_ID}}</td>
<th>{{result.First_Name}}</th>
<th>{{result.Middle_Name}}</th>
<th>{{result.Last_Name}}</th>
<th>{{result.Address}}</th>
</tr>
</tbody>
</table>
</div>
and in script
computed: {
filteredList() {
return this.results.filter(customer => {
customer.Memb_ID.toLowerCase().includes(this.search.toLowerCase());
});
}
},

Laravel 5 - Download Excel file of a View

I'm working on adding an export/downloading feature to a Laravel 5 application. I found the Laravel-Excel library (http://www.maatwebsite.nl/laravel-excel/docs), which seems perfect -- ideally, I will be able to take a Laravel View or html and make a downloadable Excel file.
So far, I've gotten the creation and storage to work. I can create an Excel file, and it's okay (it's the right data and View), and on the server in storage/exports/ I see "Report.xls" - which is right save path. The issue I'm having is I cannot seem to download the file through the browser after creating it.
The Laravel-Excel library has ->download('xls') and ->export('xls') methods, but these only seems to return the raw content, which is visible in the developer's console:
On the right, you can see the file was created and stored as "Report.xls", and presumably the raw content is the right content - but I don't know why it's just spitting raw content into the console. I can open the Report.xls file in Excel, so I know it's not corrupted.
I also tried to use the Laravel 5 Response::download() function and set headers for the download, but it also spit out raw content in the console instead of downloading the file:
The code I'm using is an AJAX call that hits a Controller method, and the controller method just triggers a Service method called "downloadReportFile()":
public function downloadReportFile($requestData, $fileType) {
$configJSON = \Report::loadConfigFile($requestData['reportName']);
$today = Carbon::today()->format('Y-m-d');
$FileViewdata = array(
'config' => $configJSON,
'html' => $requestData['report_html']
);
\Excel::create("Report", function($excel) use ($FileViewdata) {
$excel->setTitle($FileViewdata['config']['title']);
$excel->setDescription($FileViewdata['config']['description']);
$excel->sheet("page 1", function($sheet) {
$sheet->loadView("reports.sample");
});
})->store('xls', storage_path('exports')); // ->export('xls');
$report_excelFilepath = storage_path('exports') . "/Report.xls";
return response()->download($report_excelFilepath, "Report.xls", [
'Content-Type' => 'application/vnd.ms-excel',
'Content-Disposition' => "attachment; filename='Report.xls'"
]);
}
The View being made into the Excel file is a simple table - the same table as in the screenshots. Here's the template/HTML of the View:
<div class="container full-width-container">
<link href="http://192.168.33.10/css/reports.css" rel="stylesheet">
<div id="results" class="row">
<div class="col-xs-12">
<h2 class="report-title">Active Products </h2>
<br>
<div class="row">
<div class="col-xs-12">
<div class="table-responsive report-component" name="table" template="table">
<table id="report-table" class="table table-striped table-bordered table-hover">
<thead>
<tr>
<td class="report-table-th">ENGINE</td>
<td class="report-table-th">PRODUCT COUNT</td>
<td class="report-table-th">PRODUCT PRICE</td>
</tr>
</thead>
<tbody>
<tr class="results-cell">
<td class="report-table-cell">
<p>Meows</p>
</td>
<td class="report-table-cell">
<p>1,234</p>
</td>
<td class="report-table-cell">
<p>781230.00</p>
</td>
</tr>
</tbody>
<tbody>
<tr class="results-cell">
<td class="report-table-cell">
<p>Paws</p>
</td>
<td class="report-table-cell">
<p>10,777</p>
</td>
<td class="report-table-cell">
<p>3919823.00</p>
</td>
</tr>
</tbody>
<tbody>
<tr class="results-cell">
<td class="report-table-cell">
<p>Meow Mobile</p>
</td>
<td class="report-table-cell">
<p>177</p>
</td>
<td class="report-table-cell">
<p>334323.00</p>
</td>
</tr>
</tbody>
<tbody>
<tr class="results-cell">
<td class="report-table-cell">
<p>Tails Cloud</p>
</td>
<td class="report-table-cell">
<p>335</p>
</td>
<td class="report-table-cell">
<p>378918923.00</p>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
Does anyone see what I might be missing to download an XLS file?
Thanks for your time!
EDIT
After doing some more research, it seems that my original workflow for downloading -- using an AJAX call to trigger -- is part of the problem. For example Download a file from Servlet using Ajax talks about AJAX storing results in JavaScript memory, which would explain why I get content in my console and not a file.
Try to add code below before Excel::create():
ob_end_clean();
ob_start();
Example code:
ob_end_clean();
ob_start();
Excel::create($filename, function($excel) use($records, $sheetname, $data) {}
This works for me.

Resources