How do I do pagination on my code in Laravel? - laravel

So my front-end Lists of Businesses are not in paginated style. But I do not know how to do it. Can anyone please help? The code I posted is in my BusinessListController.php
BusinessListController.php
`<?php
namespace App\Http\Controllers;
use App\Models\Business;
use App\Models\Category;
use App\Models\Location;
use Illuminate\Http\Request;
class BusinessListController extends Controller
{
public function index(Request $request)
{
$businesses = Business::query()
->with('location')
->whereFilters($request->only(
['search', 'category', 'location']
))
->get();d
return view('pages.business-list', [
'businesses' => $businesses,
'locations' => Location::all(),
'categories' => Category::all()
]);
}
}`
And then here is the code for my view blade front-end
Business-List.blade.php
<div class="row business-list-row mx-auto">
#foreach ($businesses as $business)
<div class="col-md-4">
<div class="card shadow border-light mb-3">
<img
src="https://cdn1.clickthecity.com/images/articles/content/5d6eba1f4795e0.58378778.jpg"
class="card-img-top" alt="...">
<div class="card-body">
<div class="d-flex justify-content-between">
<div>
<h4 class="card-title h6" style="font-weight: bold;">
{{Str::limit($business->name, 20, $end='...')}}
</h4>
<div class="">
<p class="card-text">
{{ $business->location?->name }}
</p>
<p class="card-text" style="color: #32a852;">
{{ $business->category?->name}}
</p>
</div>
</div>
<div class="align-self-center">
<a href="{{ route('store', $business->id) }}" class="btn btn-info stretched-link">
Visit
</a>
</div>
</div>
</div>
</div>
</div>
#endforeach
</div>

So you need to do three things.
In Controller:
$businesses = Business::query()
->with('location')
->whereFilters($request->only(
['search', 'category', 'location']
))
->paginate(15);
put the number of items you need on a single page. here I put 15.
Put this under the </div> of your list.
{{ $business->links() }}
Put this inside the App\Providers\AppServiceProvider boot method.
use Illuminate\Pagination\Paginator;
public function boot()
{
Paginator::useBootstrapFive(); // or
Paginator::useBootstrapFour();
}
This depends upon which version of Bootstrap you are using.
Still confused? Checkout Laravel Pagination Documentation

Just remove ->get();d and add paginate
example
ModelName()->paginate();

Related

How to fix DELETE method not working in Laravel

My delete method is not deleting from the database and I can't seem to see what it is I'm missing in my code when I click on delete. I've provide my blade file, controller and wweb.php file below, any assistance will be highly appreciated.
Blade File
<div class="row max-inner">
#foreach ($tshirts as $tshirt)
#auth
<form action="{{ route('t-shirtsAdmin.destroy', $tshirt) }}" method="POST">
#csrf
#method('DELETE')
<button type="submit" class="btn btn-danger btn-lg">DELETE</button>
</form>
#endauth
<div class="columns col-6 collection-item">
<div class="row">
<a href="#">
<div class="slider">
#foreach (json_decode($tshirt->filenames) as $picture)
<div>
<img src="{{ asset('files/' . $picture) }}" alt="kids top" loading="lazy">
</div>
#endforeach
</div>
<div>
<div>
<div class="columns col"><i class="fas fa fa-child"></i> {{ $tshirt->gender }} top </div>
<div class="columns col"><i class="fas fa fa-calendar"></i> {{ $tshirt->age }} Years</div>
<div class="columns col"><i
class="fas fa fa-tag"></i>
Kshs 250</div>
</div>
<div class="row" style="display: flex; text-align: center; ">
<div class="columns col"><i class="fas fa fa-phone"></i> 0700 00000</div>
</div>
</div>
</a>
</div>
</div>
#endforeach
</div>
web.php
Route::resource('t-shirtsAdmin', 'App\Http\Controllers\TshirtController');
CONTROLLER
<?php
namespace App\Http\Controllers;
use App\Models\Tshirt;
use Illuminate\Http\Request;
class TshirtController extends Controller
{
public function destroy(Tshirt $tshirt)
{
$tshirt->delete();
return redirect(route('t-shirts'))->with('flash', 'T-shirt Deleted Successfully');
}
}
ok , this problem because model binding , you can solve this by 2 way first :-
public function destroy($id)
{
Tshirt::find($id)->delete();
// or Tshirt::destroy($id);
return redirect(route('t-shirts'))->with('flash', 'T-shirt Deleted Successfully');
}
second :- for route binding to work you should have type-hinted variable names match a route segment name, as the doc required : so your method will be like this :-
public function destroy(Tshirt $t-shirtsAdmin)
{
// $t-shirtsAdmin is the name of the router
$t-shirtsAdmin->delete();
return redirect(route('t-shirts'))->with('flash', 'T-shirt Deleted Successfully');
}
you can find the route name var , when you run
php artisan route:list , you will find the var like this : t-shirtsAdmin/{t-shirtsAdmin} so you should use it in controller to bind it.
You cant just call the $tshirt param and expect it to delete, try something like this:
$id = $tshirt->id;
Tshirt::destroy($id);
return redirect(route('t-shirts'))->with('flash', 'T-shirt Deleted Successfully');

How to compare a value from the search bar to the one from the database in laravel

I am trying to use the search box in my Laravel project but I keep getting the same error since morning
Here is my Search controller
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class SearchController extends Controller
{
public function index()
{
return view('search.index');
}
public function Search(Request $request)
{
$serial_number= $request->input('search');
$results =DB::table('animals')->where(function ($query) use ($serial_number) {
$query->where('serial_number','LIKE',"%$serial_number%");
})->latest()->get();
return view('search',compact('results'));
}
}
My routes
Route::get('/search','SearchController#index')->name('search');
Route::post('/search','SearchController#search')->name('search');
and finally my view
#extends('layouts.app')
#section('content')
<form action="{{ route('search') }}" method="POST">
<div class="p-1 bg-light rounded rounded-pill shadow-sm mb-4">
<div class="input-group">
<input type="search" name="search" placeholder="Here the animal serial number..." aria-describedby="button-addon1" class="form-control border-0 bg-light">
<div class="input-group-append">
<button id="button-addon1" type="submit" class="btn btn-link text-primary"><i class="fa fa-search"></i></button>
</div>
</div>
</div>
</form>
#if($results)
<div class="container">
<div class="row justify-content-center">
<div class="col-md-8">
<div class="card">
<div class="card-header">
<h3>Details for the animal</h3>
</div>
<div class="card-body">
<div class="col-12">
<p><strong>Id: </strong>{{ $results->id }}</p>
<p><strong>Animal: </strong>{{ $results->type->category }}</p>
<p><strong>Gender: </strong>{{ $results->gender }}</p>
<p><strong>Place Of Birth: </strong>{{ $results->user->address->city }}</p>
<p><strong>Farm: </strong>{{ $results->user->name }}</p>
<p><strong>Date: </strong>{{ $results->created_at }}</p>
</div>
</div>
</div>
</div>
</div>
</div>
#endif
#endsection
For me, I think that the problem is in the controller on that line $result which makes the view give the error
419|Page Expired or "Facade\Ignition\Exceptions\ViewException
Undefined variable: results (View:
/Users/macair13/MeatracProject/resources/views/search/index.blade.php)"
You need to include the CSRF token or exclude that URL from the CSRF token check.
<form ...>
#csrf
...
</form>
Laravel 6.x Docs - CSRF
Also you are not passing a results variable to your 'search' view from the Controller's index method. You will need to check if $results isset in your view or pass it to your view.
public function view (Request $request)
{
$search=$request['search'] ?? "";
if($search !=""){
//where
$data=File::where('id','like','%'.$request->search.'%')
->orwhere('name','like','%'.$request->search.'%')
->orwhere('file','like','%'.$request->search.'%')->get();
}
else{
$data = File::all();
}
$p = compact('data','search');
return view('upload_data')->with($p);
// $data = File::all();
// return view('upload_data',compact('data'));
}

How to include a sidebar in Laravel to show on all pages

I want to show a sidebar that displays data from the database across all my pages in Laravel, but I keep getting this error:
Undefined variable: products (View:
C:\xampp\htdocs\shop\resources\views\pages\sidebar.blade.php) (View:
Sidebar
#extends('layouts.app')
<nav class=" d-none d-md-block bg-light sidebar">
<div class="sidebar-sticky">
<form>
<div class=" input-group">
<input class="form-control" type="text" placeholder="Search...">
<button type="submit" class="btn btn-primary" value="search">Search</button>
</div>
</form>
#foreach($products as $product)
<span id="catName">{{ $product->name }}</span>
<h2>No category to show</h2>
#endforeach
</div>
</nav>
Controller
public function index()
{
$product = Product::get();
return view('pages.sidebar', ['products' => $product]);
}
Route
Route::resource('sidebar','SidebarController');
app.blade.php
<div class="col-md-4 col-lg-4 col-sm-12">
#include('pages.sidebar')
</div>
You can either do #include() or your can return it via a controller, you cannot do both. I think you might be a little mixed up with the structure of your project.
If you are using #include it isn't going to hit a controller. So in theory, you would need to include ['products' => $products] on every controller method.
Here is how I would do it:
sidebar.blade.php:
<nav class=" d-none d-md-block bg-light sidebar">
<div class="sidebar-sticky">
<form>
<div class=" input-group">
<input class="form-control" type="text" placeholder="Search...">
<button type="submit" class="btn btn-primary" value="search">Search</button>
</div>
</form>
#foreach($products as $product)
<span id="catName">{{ $product->name }}</span>
<h2>No category to show</h2>
#endforeach
</div>
</nav>
app.blade.php:
<div class="col-md-4 col-lg-4 col-sm-12">
#include('pages.sidebar')
</div>
Create a new file (or use an existing one) for a home page inside the pages folder, we will call it home.blade.php
home.blade.php:
#extends('layouts.app')
Change the view you are returning in the controller to new home.blade.php file.
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class HomeController extends Controller
{
public function index()
{
$product = Product::get();
return view('pages.home', ['products' => $product]);
}
}
I finally have to use view composer to solve this problem. Thank you

Two controllers one route laravel

I can currently show the index page along with a list of posts. The user can select a post to view post details. For this I have:
Routes:
Route::get('/', 'PostsController#showPosts');
Route::get('post/{slug}', 'PostsController#showPostDetails');
Controller:
<?php
namespace App\Http\Controllers;
use App\Post;
use Illuminate\Http\Request;
class PostsController extends Controller
{
public function showPosts()
{
$posts = Post::simplePaginate(2);
return view('index', ['posts' => $posts]);
}
public function showPostDetails($slug)
{
$post = Post::findBySlug($slug);
return view('post.show',['post'=>$post]);
}
}
Model:
public static function findBySlug($slug)
{
return static::where('slug', $slug)->first();
}
index
#extends('layouts.index')
#section('header')
<!-- Page Header -->
<header class="masthead" style="background-image: url('img/home-bg.jpg')">
<div class="overlay"></div>
<div class="container">
<div class="row">
<div class="col-lg-8 col-md-10 mx-auto">
<div class="site-heading">
<h1>Train Testing</h1>
<span class="subheading">Testing Times</span>
</div>
</div>
</div>
</div>
</header>
#stop
#section('content')
<div class="row">
<div class="col-lg-8 col-md-10 mx-auto">
#foreach ($posts as $post)
#include('partials.post', ['post' => $post])
#endforeach
{{ $posts->links() }}
</div>
</div>
#stop
partials/post.blade.php
<div class="post-preview">
<a href="/post/{{ $post->slug }}">
<h2 class="post-title">
{{ $post->title }}
</h2>
<h3 class="post-subtitle">
{{ $post->excerpt }}
</h3>
</a>
<p class="post-meta">Posted by
{{ $post->author->name }}
on {{ $post->created_at->format('l d F, Y') }}</p>
</div>
<hr>
I now want to show the posts on all other pages. My other pages currently have the route Route::get('{slug}', 'PagesController#show'); And it makes sense initially to refer back to existing code so use Route::get('{slug}', 'PostsController#showPosts'); like I did on the home page to display posts there.
However I am not sure of the best way to deal with this as I believe you can not have two controllers for one route.
For other pages I currently have:
Controller:
<?php
namespace App\Http\Controllers;
use App\Page;
use Illuminate\Http\Request;
class PagesController extends Controller
{
public function show($slug)
{
$page = Page::findBySlug($slug);
return view('page', ['page' => $page]);
}
}
page.blade:
#extends('layouts.index')
#section('header')
<!-- Page Header -->
<header class="masthead" style="background-image: url('/storage/{{ $page->image }}')">
<div class="overlay"></div>
<div class="container">
<div class="row">
<div class="col-lg-8 col-md-10 mx-auto">
<div class="page-heading"> <h1>{!! $page->title !!}</h1>
<span class="subheading"></span>
</div>
</div>
</div>
</div>
</header>
#stop
#section('content')
<!-- Main Content -->
<div class="container">
<div class="row">
<div class="col-lg-8 col-md-10 mx-auto">
{!! $page->body !!}
</div>
</div>
</div>
#stop
Pages Controller:
use App\Page;
use App\Post;
use Illuminate\Http\Request;
class PagesController extends Controller
{
public function show($slug)
{
$posts = Post::simplePaginate(2);
$page = Page::findBySlug($slug);
return view('page', ['page' => $page, 'posts' => $posts]);
}
Then in page.blade.php I can call $posts without any errors:
#foreach ($posts as $post)
#include('partials.post', ['post' => $post])
#endforeach
{{ $posts->links() }}
Not sure if this is the neatest way but it works.

Laravel allow links on message

I need allow links in messages, when user send message. How I can do this?
#foreach($mess as $message)
<li data-mid="{{ $message->id }}">
<div class="row margin-left-none margin-right-none">
<div class="col-md-2 padding-right-none">
<div class="avatar-user text-center">
<img src="{{ $message->sender->avatar }}" alt="$message->sender->name">
</div>
</div>
<div class="col-md-10 padding-left-none">
<div class="user-name">
<span>{{ $message->sender->name }}
#if(Helper::getOnlineUser($message->sender->id))
<i data-toggle="tooltip" title="Онлайн" class="material-icons online">fiber_manual_record</i>
#else
<i data-toggle="tooltip" title="Оффлайн" class="material-icons offline">fiber_manual_record</i>
#endif
<span class="date float-right">{{ $message->created_at->formatLocalized('%H:%m') }}</span></span>
</div>
<div class="message">
{{ $message->body }}
</div>
</div>
</div>
</li>
#endforeach
This is view of messages.
How I can allow links?
Example: http://example.com in messages =>
http://example.com
I need {!! $message->body !!} ? Or How?
In controller:
$mess = Chat::conversations($conversation)->for($user)->getMessages($limit, $request->page);
I use this package: https://github.com/musonza/chat
There are built in PHP functions to handle this:
<div class="message">
{!! strip_tags($message->body, '<a>') !!}
</div>
Where the second argument is your whitelist.
This has the following advantages:
You're not messing with regex
You're still using blade {!!!!}
You're using well tested code dev'ed by the core team
You can do it by using following php function in your blade,
<?php
function getDataWithURL($text){
// The Regular Expression filter
$reg_exUrl = "/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/";
// Check if there is a url in the text
if(preg_match($reg_exUrl, $text, $url)) {
// make the urls hyper links
echo preg_replace($reg_exUrl, "".$url[0]." ", $text);
} else {
// if no urls in the text just return the text
echo $text;
}
}
?>
You just need to add this code in your blade file and then you can check and replace the links in your text like this,
<div class="message">
<?php getDataWithURL($message->body);?>
</div>
I hope you will understand.

Resources