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

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

Related

Laravel ErrorException Undefined variable $product

i have littel problem in my code, i dont know write mastake but i check my code is good
This ShopController
`
public function show($id)
{
$product = Product::findOrFail($id);
return view('shop.show');
}
`
this my route
`
Route::get('/shop/detail/{id}', 'ShopController#show');
`
this my view
`
<div class="container">
<h2 class="title">{{$product->name}}</h2>
<hr>
<div class="row">
<div class="wrapper">
<div class="col-lg-4" id="picture">
<img src="{{asset($product->image)}}" alt="" height="200" width="200">
</div>
</div>
<div class="col-lg-4 desc">
<h4 id="description">Description</h4>
<p>{{$product->desc}}</p>
</div>
<div class="col-lg-4">
<div class="kartu">
<p>Harga</p>
<h2>Rp {{number_format($product->price)}}</h2>
<form action="" method="POST">
#csrf
<input type="hidden" value="" name="item_id">
<input type="submit" class="btn btn-primary" value="Add to Cart">
</form>
</div>
</div>
</div>
</div>
`
I have checked my code and there are no errors
You don't pass the product to the view. You need to compact the variable like this in the controller:
public function show($id)
{
$product = Product::findOrFail($id);
return view('shop.show', compact('product'));
}
you are getting product from database in $product variable, but not passing that variable to your view. There are several ways to pass variables to view.
return view('shop.show', compact('product'));
OR
return view('shop.show', ['product' => $product]);
OR
return view('shop.show', get_defined_vars());
get_defined_vars() is built-in php function, by using this function any numbers of variables declared in method, all will be passed to view

How do I do pagination on my code in 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();

How to add form action to laravel function

I have a website I am currently editing tht was built with laravel. I have have a page that displays a "details of shipped package"
I added a form to page to update the current location of the shipped package on the details page.
<div class="row mb-30">
<div class="col-lg-12 mt-2">
<div class="card border--dark">
<h5 class="card-header bg--dark">#lang('Courier Location')</h5>
<div class="card-body">
<form action="{{route('....')}}" method="POST">
#csrf
<div class="modal-body">
<div class="form-group">
<label for="current_location" class="form-control-label font-weight-bold">#lang('Current Location')</label>
<input type="text" class="form-control form-control-lg" name="current_location" value="{{__($courierInfo->current_location)}}" required="">
</div>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn--primary"><i class="fa fa-fw fa-paper-plane"></i>#lang('Update')</button>
</div>
</form>
</div>
</div>
</div>
I have also added the update function in the controller
public function courierUpdate(Request $request, $id)
{
$request->validate([
'current_location' => 'required',
]);
$courierInfoUpdate =CourierInfo::findOrFail($id);
$courierInfoUpdate->current_location = $request->current_location;
$courierInfoUpdate->save();
$notify[] = ['success', 'Courier location info has been updated'];
return back()->withNotify($notify);
}
I am having problem with the laravel route to call that should be added as form action.
Declare a route on the web.php
Route::post('/courier-Update/{id}','App\Http\Controllers\YourControllerName#courierUpdate')->name('courier.Update');
and now just call this route in your form and also pass the id of that courier
like this:
route('courier.Update',$courier->id)
You can add a new route in routes/web.php
//import your controller at Beginning of the file
use App\Http\Controllers\YourController;
Route::post('update_location/{id}', [YourController::class, 'courierUpdate'])->name('updateLocation');
//or
Route::post('update_location/{id}', 'YourController#courierUpdate')->name('updateLocation');
And then in your blade view
<form action="{{ route('updateLocation', [ 'id' => $id]) }}" method="POST">
#csrf
</form>

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'));
}

Resources