Laravel pagination does not exist
I'm trying to create a pagination, the problem is, is that when I trying to create the pagination I get this error
Method Illuminate\Database\Eloquent\Collection::pagination does not exist.
I'm using laravel and livewire.
This is my code
$products = $this->category->products->pagination(10);
This is in my Category model
public function products()
{
return $this->hasMany(Product::class);
}
UPDATE
This is my whole code for my livewire
<?php
namespace App\Http\Livewire\Categories;
use Illuminate\Pagination\Paginator;
use Livewire\Component;
class Show extends Component
{
public $category;
public function render()
{
$products = $this->category->products->paginate(10);
return view('livewire.categories.show', ['category' => $this->category, 'products' => $products]);
}
}
and my livewire.categories.show blade file
<table class="min-w-full divide-y divide-gray-200">
<tbody>
@foreach($products as $product)
<tr>
<td>
{{ $product->name }}
</td>
</tr>
@endforeach
</tbody>
</table>
<div>
{{ $products->links() }}
</div>
1 answer
-
answered 2021-01-11 06:19
IGP
You forgot to use the
WithPagination
trait as stated in the Livewire docs.<?php namespace App\Http\Livewire\Categories; use Illuminate\Pagination\Paginator; use Livewire\Component; use Livewire\WithPagination; class Show extends Component { use WithPagination; public $category; public function render() { $products = $this->category->products()->paginate(10); return view('livewire.categories.show', ['category' => $this->category, 'products' => $products]); } }
See also questions close to this topic
-
Select XML file and delete it after submit
As for an assignment I'll have to select an XML file from a specific folder and remove it by clicking a button. So far I've tried everything I could find on the internet and the document still remains in the folder.
(I'm still a student, so apologies in advance if there's a clear solution)
Test example code
<form method="POST" enctype="multipart/form-data"> <input type="file" name="file"> <input type="submit" value="Delete"> </form> <?php if (isset($_POST['submit'])) { $file = $_Files["file"]; unlink("s_orderlist/". $file["name"]); } ?>
Edit After your helpful comments I'm going to try a different approach that's more server friendly. Thank you!
-
Changing image every 5-10 seconds
Ok, so, I am trying to get a profile picture to change every couple of seconds on my website. It is written in php/css. I've read over 100 different posts and websites and have tried a dozen different ways to get this to work, but nothing I've tried works. Even if the coding works in places like JSFiddle, I cannot get it to work on my site. I have tried jQuery, cycles, cycles2, plain css and multiple types of each.
code from module
<div class="col-6 col-md-4"> <div class="fling-minislide"> <img src="<?=SITE_URL;?>/img/lapis.webp" class="lazy rounded-circle staff" alt="Slide 2"/> <img src="<?=SITE_URL;?>/img/dragon.webp" class="lazy rounded-circle staff" alt="Slide 1"/> </div> <p class="staff-name">theLapisFox</p> <p class="staff-role">Developer</p> </div>
css code
.fling-minislide {width:350px; height:300px; overflow:hidden; position:relative; } .fling-minislide img{ position:absolute; animation:fling-minislide 20s infinite; opacity:0; width: 100%; height: auto;} @keyframes fling-minislide {25%{opacity:1;} 40%{opacity:0;}} .fling-minislide img:nth-child(2){animation-delay:0s;} .fling-minislide img:nth-child(1){animation-delay:10s;}
I got the above from https://www.hyde-design.co.uk/joomla-bites/80-create-a-css-slideshow-no-javascript-required and, while it, plus all the other solutions I've tried, works just fine for them, instead of getting a slideshow, both images are shown on screen when adding the code to my site.
I know there are hundreds of questions on this board alone asking about this same exact issue, I've read most of them, but for some reason, it just refuses to work for me and I hope someone can tell me what could possibly be the issue.
Edit:
As further proof of other ways I have tried; http://jsfiddle.net/52RHm/ When adding it to my site, it didn't work either, but yet it works just fine in JSFiddle.
-
Display Blog-Post on another side using PHP
I have a problem with the PHP syntax.
I try to create a Blog-System. The idea is that someone click on a special blogpost and then get linked to page called view.php. On that page only that blogpost should display witch the user clickt on.
I managed to get the id of the blogpost within the url to the
view.php
page (e.g.view.php?id=21
). The problem is that I dont use a form on my index to display all posts, so I think the$_GET
varible doesn't work. I believe that a have to use a combination of thevar_dump()
,parse_url()
andparse_str()
functions to retrieve the id of the blogpost onview.php
in order to display only that specific post. I do not know how though. Maybe I can use the$_SERVER
varible to get the data from the URL?This is my index.php:
<?php while ($row = mysqli_fetch_assoc($result)) { ?> <div style=""> <a href="view.php?id=<?php echo $row['idGallery']; ?>"> <p><?= $row['titleGallery'] ?></p> <img class="img-fluid" src="<?= 'img/gallery/' . $row['imgFullNameGallery'] ?>" width="100" height="100" /> </a> <p><?= $row['descGallery'] ?></p> </div> <?php } ?>
And this is the view.php:
<?php include_once "includes/dbh.inc.php"; $BlogPostSQLPrepared = mysqli_prepare($conn, "SELECT idGallery AS id, titleGallery, descGallery, imgFullNameGallery, orderGallery WHERE id = ?"); mysqli_stmt_bind_param($BlogPostSQLPrepared, "i", $_GET['id']); mysqli_execute($BlogPostSQLPrepared); $result = mysqli_stmt_get_result($BlogPostSQLPrepared); if($row = mysqli_fetch_array($result)){ $Post[$row['id']]['titleGallery'] = $row['titleGallery']; $Post[$row['id']]['descGallery'] = $row['descGallery']; $Post[$row['id']]['orderGallery'] = $row['orderGallery']; $Post[$row['id']]['imgFullNameGallery'] = $row['imgFullNameGallery']; }
-
web app to mobile app using react native?
im trying to develope a delivery web application with bootstrap in frontend side and laravel in backend side. at last i must have a mobile app for ios and android . its not a complicated program . can I do it using react native?
-
How to define name for slug?
Look at my codes.
web.php
Route::get('/{pageSlug}', 'PageController@about')->name('about');
RouteServiceProvider.php
public function boot() { Route::bind('pageSlug', function ($value) { return Page::whereSlug($value)->firstOrFail(); }); parent::boot(); }
blade
<a class="nav-link" href="{{ route('about') }}">About</a>
I see this error
Missing required parameters for [Route: about] [URI: pageSlug}]. (View: C:\xampp3\htdocs\projects\resources\views\Home\layouts\header.blade.
-
How to show date-time in laravel field?
Technology - Laravel8 How can I show value date-time in field?
I tried to do this in this way, but it wasn't successfull.
{!! Form::input('datetime-local', 'startdatetime', $auction->startdatetime, array('class' => 'form-control')) !!}
Example on value of ($auction->startdatetime) => "2021-01-24 08:00:00"
-
automatic login from controller in laravel 8
I need to make login exactly as laravel Auth Facades does in the following way. I will have some url say "HOST/makeLogin?someToken=xxtrypturan";
Now in controller I have a function as follow:
$creatorOfTheShop = $user->find($request->get('someToken')); //this will give user from db Auth::login($creatorOfTheShop);
Now I want this login to create web session as laravel does in default login. How can I do so, so that I can use auth guards in routes. I wont have any login page, so I am adopting this approach. Thanks
-
Laravel 8.x - Cache query using with() method
1) A simple code that I use to cache an expensive query is something like:
$query = User::where('id', '=', 3); $cacheKey = md5($query->toSql()); // It is: "SELECT * FROM users WHERE id=3;" $users = Cache::remember($cacheKey, 120, function () use ($query) { return $query->get(); });
the query executed is:
SELECT * FROM users WHERE id=3;
2) Now, when I use the
with()
method, the code will be:$query = User::with('car')->where('id', '=', 3); $cacheKey = md5($query->toSql()); // It is ALWAYS: "SELECT * FROM users WHERE id=3;" $users = Cache::remember($cacheKey, 120, function () use ($query) { return $query->get(); });
the query executed are:
SELECT * FROM users WHERE id=3; SELECT * FROM cars where cars.id in (1, 2, 3, 4, 5, ...);
The problem is that the
$cacheKey
(equal to:$query->toSql()
) doesn't consider the all the Eager Loading queries... and when thewith()
changes, the output is the same.For example, If I run:
$query = User::with('bike')->where('id', '=', 3); $cacheKey = md5($query->toSql()); // It is ALWAYS: "SELECT * FROM users WHERE id=3;" $users = Cache::remember($cacheKey, 120, function () use ($query) { return $query->get(); });
the cache exists and return a incorrect output.
What is the best practice to cache quark using
with()
method?Thank you,
-
credentials do not match our records
I am currently working on POS in laravel 8. I am having an error when I login in that "credentials do not match our records" When I login in through the default Register page than it works fine but when I register through internal panel than the data goes to the database but I face error when I log in.
code for registration through panel: public function store(Request $request) { $users = new User; $users->name = $request->name; $users->email = $request->email; $users->password = Hash::make($request->name); // $users->password = bcrypt($request->name); $users->is_admin = $request->is_admin; $users->save(); if($users){ return redirect()->back()->with('User Created Successfully'); } return redirect()->back()->with('User Failed Created'); } default register code: protected function create(array $data) { return User::create([ 'name' => $data['name'], 'email' => $data['email'], 'password' => Hash::make($data['password']), ]); }
-
Having issue with Livewire and an inline js script for zooming image
been stuck here for 2 days now, please advise.
I have this Livewire ProductDetail modal that shows when Livewire
public $show = true
and I have a listener listening for aviewProduct
event and when the event is received theviewProduct
public method is called and the product is assigned topublic $product
then$this->show = !this->show
and the modal is displayed as expected.The problem is that I have a js script in the blade file that implements a zoom function on the product image when you hover with the mouse and this gets all messed up.
I have tried different approaches using Livewire events and also Alpine js but still no luck.
Livewire ProductDetail Component
<?php namespace App\Http\Livewire; use App\Models\Product; use App\Updatable; use Livewire\Component; class ProductDetail extends Component { use Updatable; public $show = false; // public $product; protected $listeners = ['viewProduct', 'cartUpdated' => '$refresh']; public function viewProduct(Product $product) { $this->product = $product; $this->show = !$this->show; } public function render() { return view('livewire.product-detail'); } }
product-detail.blade.php
@php $cartContent = Cart::content(); @endphp <div wire:igone x-data="{ show: @entangle('show'), }" x-show="show" x-cloak class="bg-black bg-opacity-50 fixed inset-0 lg:flex lg:items-center overflow-scroll z-10"> @if (isset($product)) <div class="bg-white lg:max-w-screen-md lg:min-h-0 min-h-screen mx-auto relative w-full xl:max-w-screen-lg rounded-md overflow-hidden"> <div class="lg:flex lg:gap-6 py-6 px-4"> <div class="w-1/2 flex items-center justify-center"> <x-image-zoom :image="$product->image" /> </div> <div class="flex-1 mt-2"> <div class="flex flex-col justify-between"> <h1 class="flex-1 text-2xl mt-1 max-w-xs leading-none"> {{ $product->name }} </h1> <div class="flex justify-start my-4"> <x-badge class="text-xl" :product="$product" /> </div> <div> <p>{{ $product->unit_size }}</p> <div class="flex items-center justify-start space-x-2 mt-3 leading-none"> <div class="font-semibold inline-flex items-baseline text-gray-700"> <span class="text-gray-500 pr-1">Ks</span> <span class="text-2xl" x-text="getFormattedPrice('{{ $product->discount_available }}', '{{ $product->discount }}', '{{ $product->price }}')" /> </div> <div x-show="ifDiscountAvailable('{{ $product->discount_available }}')"> <span class="line-through tracking-tight text-gray-500 font-semibold">{{ $product->formatted_price }}</span> </div> </div> </div> <p class="text-sm text-gray-600 my-8"> {{ $product->description }} </p> </div> </div> </div> <div class="bg-gray-200 h-32 px-3 py-3"> Footer </div> </div> @endif </div>
The problem component please have a look at this and advise
<x-image-zoom :image="$product->image" />
passing the path to the image<div> <div x-data="initiate()" x-on:mouseenter="zoomImage('myimage', 'myresult')" x-on:mouseleave="removeCreatedElements()" class="img-zoom-container w-full h-full relative"> <img id="myimage" src="{{ asset('storage/'.$image) }}"> <div id="myresult" class="img-zoom-result"></div> </div> </div> <script> function initiate() { return { zoomImage(imgID, resultID) { var img, lens, result, cx, cy; img = document.getElementById(imgID); result = document.getElementById(resultID); result.setAttribute('class', 'absolute inset-0'); lens = document.createElement("DIV"); lens.setAttribute("class", "absolute border-2 border-accent w-52 h-52"); lens.setAttribute('id', 'zoomLense'); img.parentElement.insertBefore(lens, img); cx = result.offsetWidth / lens.offsetWidth; cy = result.offsetHeight / lens.offsetHeight; result.style.backgroundImage = "url('" + img.src + "')"; result.style.backgroundSize = (img.width * cx) + "px " + (img.height * cy) + "px"; lens.addEventListener("mousemove", moveLens); img.addEventListener("mousemove", moveLens); result.addEventListener("mousemove", moveLens); lens.addEventListener("touchmove", moveLens); img.addEventListener("touchmove", moveLens); result.addEventListener("touchmove", moveLens); function moveLens(e) { var pos, x, y; e.preventDefault(); pos = getCursorPos(e); x = pos.x - (lens.offsetWidth / 2); y = pos.y - (lens.offsetHeight / 2); if (x > img.width - lens.offsetWidth) { x = img.width - lens.offsetWidth; } if (x < 0) { x = 0; } if (y > img.height - lens.offsetHeight) { y = img.height - lens.offsetHeight; } if (y < 0) { y = 0; } /*set the position of the lens:*/ lens.style.left = x + "px"; lens.style.top = y + "px"; /*display what the lens "sees":*/ result.style.backgroundPosition = "-" + (x * cx) + "px -" + (y * cy) + "px"; } function getCursorPos(e) { var a, x = 0, y = 0; e = e || window.event; /*get the x and y positions of the image:*/ a = img.getBoundingClientRect(); /*calculate the cursor's x and y coordinates, relative to the image:*/ x = e.pageX - a.left; y = e.pageY - a.top; /*consider any page scrolling:*/ x = x - window.pageXOffset; y = y - window.pageYOffset; return { x: x, y: y }; } }, removeCreatedElements() { document.getElementById('zoomLense').remove(); document.getElementById('myresult').style.backgroundImage = 'none'; } } } </script>
The above script works if I do the following in
ProductDetail.php
but when products change the js gets messed up<?php namespace App\Http\Livewire; use App\Models\Product; use App\Updatable; use Livewire\Component; class ProductDetail extends Component { use Updatable; public $show = false; // public $product; protected $listeners = ['viewProduct', 'cartUpdated' => '$refresh']; public function viewProduct(Product $product) { // $this->product = $product; $this->show = !$this->show; } public function render() { // return view('livewire.product-detail'); return view('livewire.product-detail', ['product' => Product::find(1)]); } }
-
How to mount a variable with an array of data in a component?
I want to pass an array of data from one component to another. I have a
UserController
component and aUserBulkDeletion
component. I have definedpublic $selected = []
in a trait,WithBulkActions
and is being imported and used in both the components. I have an input checkbox, wire modeled toselected
with value$user->id
within the foreach loop.I need to pass an array of data, which a user selects, from the
UserController
component and pass it toUserBulkDeletion
component. I have mounted the$selected
variable, still its not working as expected. Please help me, thank you for your time!- Http/Livewire/Trait/WithBulkActions
trait WithBulkActions { public $selectPage = false; public $selectAll = false; public $selected = []; public function renderingWithBulkActions() { if ($this->selectAll) $this->selectPageRows(); } public function updatedSelected() { $this->selectAll = false; $this->selectPage = false; } public function updatedSelectPage($value) { if ($value) return $this->selectPageRows(); $this->selectAll = false; $this->selected = []; } public function selectPageRows() { $this->selected = $this->rows->pluck('id')->map(fn($id) => (string) $id); } public function selectAll() { $this->selectAll = true; } public function getSelectedRowsQueryProperty() { return (clone $this->rowsQuery) ->unless($this->selectAll, fn($query) => $query->whereKey($this->selected)); } }
- Http/Livewire/UserManagement/LogicalComponent/UserBulkDeletion
class UserBulkDeletion extends Component { use WithCachedRows, WithSorting, WithBulkActions, WithPerPagePagination; public User $user; public $showUserBulkDeletionModal = false; public $filters = [ 'search' => "", 'email' => null, 'role' => '', 'date-min' => null, 'date-max' => null, ]; protected $listeners = ['deleteUserBulk']; public function mount($selected) { $this->selected = $selected; } public function deleteUserBulk() { $this->useCachedRows(); $this->showUserBulkDeletionModal = true; } public function confirmDeleteBulk() { $deleteCount = $this->selectedRowsQuery->count(); foreach ($this->selectedRowsQuery->get() as $queryRow) { $queryRow->roles()->detach(); } $this->selectedRowsQuery->delete(); $this->showUserBulkDeletionModal = false; $this->notify('You\'ve deleted '.$deleteCount.' users'); $this->emit('sectionRefresh'); } public function getRowsQueryProperty() { $query = User::query() ->when($this->filters['email'], fn($query, $email) => $query->where('email', 'like', '%'.$email.'%')) ->when($this->filters['role'], fn($query, $role) => $query->whereHas('roles', fn ($query) => $query->where('id', $role))) ->when($this->filters['search'], fn($query, $search) => $query->where('name', 'like', '%'.$search.'%')) ->when($this->filters['date-min'], fn($query, $created_at) => $query->where('created_at', '>=', Carbon::createFromFormat('d/m/Y', $created_at))) ->when($this->filters['date-max'], fn($query, $created_at) => $query->where('created_at', '<=', Carbon::createFromFormat('d/m/Y', $created_at))); return $this->applySorting($query); } public function getRowsProperty() { return $this->cache(function () { return $this->applyPagination($this->rowsQuery); }); } public function render() { return view('livewire.backend.management.audience-management.logical-component.user-bulk-deletion'); } }
- views/livewire/user-management/user-controller
<div class="space-x-4 flex items-center"> <x-dropdown label="Bulk Actions"> <x-dropdown.item type="button" wire:click="$emit('deleteUserBulk')" class="flex items-center space-x-2"> <x-icon.trash class="text-cool-gray-400" /> <span>Delete</span> </x-dropdown.item> </x-dropdown> </div> <x-table> <x-slot name="head"> <x-table.heading class="pr-0 w-8"> <x-input.checkbox wire:model="selectPage" /> </x-table.heading> <x-table.heading sortable multi-column wire:click="sortBy('id')" :direction="$sorts['id'] ?? null" class="pr-0 w-8">ID</x-table.heading> <x-table.heading sortable multi-column wire:click="sortBy('name')" :direction="$sorts['name'] ?? null">Name</x-table.heading> </x-slot> <x-slot name="body"> @forelse($users as $key => $user) <x-table.row wire:key="row-{{ $user->id }}" wire:loading.class.delay="opacity-50"> <x-table.cell class="pr-0"> <x-input.checkbox wire:model="selected" value="{{ $user->id }}" /> </x-table.cell> <x-table.cell>{{ $users->firstitem() + $key }}</x-table.cell> <x-table.cell>{{ $user->name }}</x-table.cell> </x-table.row> @endforelse </x-slot> </x-table> @push('modals') <!-- Delete User Bulk Modal --> <livewire:backend.management.audience-management.logical-component.user-bulk-deletion :selected="$selected" /> @endpush
-
How to Pass Data From Alpine Js To Livewire Component?
I'm new at Alpine Js and Livewire. And I'm trying to use this pen with form submit:
https://codepen.io/atomgiant/pen/QWjWgKz
I couldn't figure it out to use this. I'm adding
wire:model="tags"
to input and usingpublic $tags;
at component but it's not working. I can't get tags data from input. There are not much examples for Alpine Js...My Blade:
<div class="flex flex-col w-full md:w-full px-3 mb-6"> <div x-data @tags-update="console.log('tags updated', $event.detail.tags)" data-tags='["aaa","bbb"]' class="max-w-lg m-6"> <div x-data="tagSelect()" x-init="init('parentEl')" @click.away="clearSearch()" @keydown.escape="clearSearch()"> <div class="relative" @keydown.enter.prevent="addTag(textInput)"> <input x-model="textInput" x-ref="textInput" @input="search($event.target.value)" class="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline" placeholder="Enter some tags"> <div :class="[open ? 'block' : 'hidden']"> <div class="absolute z-40 left-0 mt-2 w-full"> <div class="py-1 text-sm bg-white rounded shadow-lg border border-gray-300"> <a @click.prevent="addTag(textInput)" class="block py-1 px-5 cursor-pointer hover:bg-indigo-600 hover:text-white">Add tag "<span class="font-semibold" x-text="textInput"></span>"</a> </div> </div> </div> <!-- selections --> <template x-for="(tag, index) in tags"> <div class="bg-indigo-100 inline-flex items-center text-sm rounded mt-2 mr-1"> <span class="ml-2 mr-1 leading-relaxed truncate max-w-xs" x-text="tag"></span> <button @click.prevent="removeTag(index)" class="w-6 h-8 inline-block align-middle text-gray-500 hover:text-gray-600 focus:outline-none"> <svg class="w-6 h-6 fill-current mx-auto" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path fill-rule="evenodd" d="M15.78 14.36a1 1 0 0 1-1.42 1.42l-2.82-2.83-2.83 2.83a1 1 0 1 1-1.42-1.42l2.83-2.82L7.3 8.7a1 1 0 0 1 1.42-1.42l2.83 2.83 2.82-2.83a1 1 0 0 1 1.42 1.42l-2.83 2.83 2.83 2.82z"/></svg> </button> </div> </template> </div> </div> </div> <div class="flex justify-between"> <button wire:click="back(5)" class="inline-flex items-center px-4 py-2 bg-gray-800 border border-transparent rounded-md font-semibold text-xs text-white tracking-widest hover:bg-gray-700 active:bg-gray-900 focus:outline-none focus:border-gray-900 focus:shadow-outline-gray disabled:opacity-25 transition ease-in-out duration-150" type="button">Back</button> <button wire:click="sixthStepSubmit" class="inline-flex items-center px-4 py-2 bg-gray-800 border border-transparent rounded-md font-semibold text-xs text-white tracking-widest hover:bg-gray-700 active:bg-gray-900 focus:outline-none focus:border-gray-900 focus:shadow-outline-gray disabled:opacity-25 transition ease-in-out duration-150" type="button">Next</button>
My Component
<?php namespace App\Http\Livewire\Projects; use App\Models\Project; class CreateProjectFormSection extends Component { public $tags; public function sixthStepSubmit() { dd($this->tags); $this->currentStep = 7; }