Pagination with search query - laravel

Controller:
public function search(Request $request)
{
$stores = Store::with('router', 'tills', 'backOffices','contacts', 'storeStatus', 'storeStatus', 'storeType', 'scos', 'fuelBrand')->where('store_name', 'like', '%' . $request['find'] . '%')->paginate(13);
return view('store.index')->with([
'stores' => $stores,
'find' => $request['find'],
]);
}
View
<div class="flex-1 mx-10">
<form action="/store/search" method="POST" name="search" role="search">
#csrf
<input id="index-view-search" name="find" type="text" placeholder="Search"
class="border rounded w-full p-1"
>
</form>
</div>
<div class="mx-3">
#if ( Route::is('store.index') )
{{ $stores->links() }}
#else
{!! $stores->appends(['find' => $find])->links() !!}
#endif
</div>
Route
Route::any('/store/search', "StoreController#search")->name('stores.search');
Can anyone tell me why I get a 404 when I click the pagination links for this code?
The route accepts post or get, I pass back the search term and the page number... /store/search?find=evans&page=2 is what the pagination instance is requesting, I cannot see what is wrong

I actually figured it out, As I have a resource controller so store/{id} is active so I need to rename the URI.

Related

Error message "The GET method is not supported for this route. Supported methods: POST." in laravel 8

Following is my controller. Method ProjectsView is to view all the listings. The second method BackendProjectSearch is for searching of projects. The first page of search result is displayed properly, but when we click on next page it gives the error "The GET method is not supported for this route. Supported methods: POST."
What should I do ?
public function ProjectsView(){
$projects = projects::orderBy('id','ASC')->paginate(15);
return view('backend.projects.projects_view',compact('projects')); }
public function BackendProjectSearch(Request $request){
$request->validate(["search" => "required"]);
$item = $request->search;
$projects = Projects::where('project_name','LIKE',"%$item%")->paginate(15);
return view('backend.projects.projects_view',compact('projects')); }
Following are the routes for both the methods :
Route::post('/backend/project/search', [ProjectsController::class, 'BackendProjectSearch'])->name('backend.project.search');
Route::get('/view', [ProjectsController::class, 'projectsView'])->name('projects.view');
View code :
<div class="col-md-8">
<div class="header-navsearch">
<form class="form-inline mr-auto" method="post" action="{{route('backend.project.search')}}">
#csrf
<div class="nav-search">
<input type="search" name="search" class="form-control header-search" placeholder="Search projects…" aria-label="Search">
<button class="btn btn-primary" type="submit"><i class="fa fa-search"></i></button>
</div>
</form>
</div>
</div>
The route for this request should be post, not get.
Example
Route::post(-----);
Also, make sure to insert a CSRF token while making the request
it means you now cannot do something like the following.
Instead, you have to do something like...
<form action="{{ route('example') }}" method="POST">
#csrf {{-- According to the version of laravel --}}
{{-- Your other codes --}}
<button type="submit" class="">Submit</button>
</form>
You have to use the below code
return redirect()->route('projects.view')->with(['projects' => $projects]);
Your route might be little change
Route::get('/view/{projects?}', [ProjectsController::class, 'projectsView'])->name('projects.view');
and In your controller, you have to change function like this
public function ProjectsView($projects = null){
if($projects!=null){
return view('backend.projects.projects_view',compact('projects'));
}
else{
$projects = projects::orderBy('id','ASC')->paginate(15);
return view('backend.projects.projects_view',compact('projects'));
}

Laravel 2 submit buttons in the same form

I am building a CRUD with Laravel. Each category hasMany attachments and each attachment belongsTo a category.
In the category.edit view I want to give the user the possibility of deleting the attachments (singularly) from the Category. I tried this method but it did not work:
Registering route for the attachment:
Route::group(['middleware' => ['auth']], function () {
Route::delete('attachment/{id}', 'AttachmentController#delete')->name('attachment');
});
Handling the delete building the AttachmentController#delete method:
class AttachmentController extends Controller
{
public function delete($id) {
$toDelete = Attachment::findOrFail($id);
$toDelete->delete();
return redirect()->back();
}
}
In the CategoryController (edit method), I fetch the attachments linked to each category to be rendered inside the view:
public function edit($category)
{
$wildcard = $category;
$category = Category::findOrFail($wildcard);
$attachments = App\Category::findOrFail($wildcard)->attachments()->get()->toArray();
return view('category.edit', [
'category' => $category,
'attachments' => $attachments
]);
}
In the view, I render the attachment and the button to delete. I am fully aware of the error of having a form inside another form, nevertheless I do not know antoher approach to submit this delete request.
// update Category form
#foreach ($attachments as $attachment)
<div class="row">
<div class="col-4">
<img style="width: 100%;" src={{ $attachment['url'] }} alt="">
</div>
<div class="col-4">
<div>
<p class="general_par general_url">{{ $attachment['url'] }}</p>
</div>
</div>
<div class="col-4">
<form action="{{ route('attachment', $attachment['id']) }}" method="POST">
#csrf
#method('DELETE')
<button type="submit" class="btn btn-danger">Delete Image</button>
</form>
</div>
</div>
<hr>
#endforeach
// end of update Category form
Should I build a deleteAttachment method inside the CategoryController? If so, how can I still submit the Delete request? Also, if any other Model in the future will have attachments, should I build a deleteAttachment method inside each controller? That is cumbersome. Thanks in advance
if you don't like to use form, then use tag:
<a class="btn btn-danger" href="{{ route('attachment', $attachment['id']) }}">Delete Image</a>
And redefine the route to Route::get(...)
(or maybe use ajax for POST method if that is required)

How to return view in controller?

I need to pull in data to my view but this doesn't work:
return view ('sub-domain', ['worker' => $worker ]);
Here is my code:
public function aerospace(Request $request , Worker $worker ){
$worker = $worker->newQuery();
if ($request->has('profession')) {
$worker->where('profession', $request->input('profession'));
}
if ($request->has('state')) {
$worker->where('state', $request->input('state'));
}
if ($request->has('local_govt')) {
$worker->where('local_govt', $request->input('local_govt'));
}
return $worker->get();
The above code brings out an array of data from the database which I can then filter with "domain/sub-domain?state=xyz"
Now when I try to pass in the data into my views using
return view ('sub-domain', ['worker' => $worker ]);
The page is loaded but no $worker data is loaded on the page. How can I pull the data? Here is my view file
<div class="row">
<form method="GET" action="">
Profession:<input type="text" name="profession"> State:<input type="text" name="state"> Local Govt:<input type="text" name="local_govt">
<button type="submit">Filter</button>
</form>
</div>
<div class="row">
#foreach ($worker as $worker)
<div class="col-lg-3 col-md-6">
<div class="member">
<div class="pic"><img src="avatar/{{$worker->avatar}}" alt=""></div>
<div class="details">
<h4>{{$worker->name}} {{$worker->l_name}}</h4>
<span>{{$worker->profession}}</span><br>{{ $worker->state }}
</div>
</div>
</div> #endforeach
</div>
I want to filter data by certain parameters, if there's a better way to do that please do let me know. But first I need the data to display.
You are returning a query instance, not a collection or singular model. That's why the get() method works. So first do:
$worker = $worker->get();

HOw to make simple search with laravel

i try to create forms search in laravel..
when the title of the title article is searched .. then the title will appear.. i am search title article form Article Table
this is my HomeController
...
public function search(Request $request){
$cari = $request->get('search');
$Title = Article::where('title', 'LIKE', '%' .$cari . '%')->paginate(10);
return view('/article/show', $cari);
}
this is my header.blade.php
**...
<div class = "col-md-4">
{!! Form::open(['method'=>'GET', 'url'=>'/article/show', 'role'=>'search']) !!}
<div class= "input-group custom-search-form">
<input type="text" class="form-control" name="search" placeholder="Judul..">
<span class="input-group-btn">
<span class="input-group-btn">
<button class="btn-btn-default" type="submit"><i class="fa fa-search"></i>Cari</button>
</span>
</span>
{!! Form::close()!! }
</div>
</div>
thi is my route..
..
Route::get('/article/show', 'HomeController#search');
.
But when i am typing on search form.. i am getting error like this
(2/2) QueryException
SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'show AND is_show = TRUE and `articles`.`deleted_at` is null' at line 1 (SQL: select count(*) as aggregate from `articles` where category_id=show AND is_show = TRUE and `articles`.`deleted_at` is null)
.
please tell me which part is wrong
Thanks...
You're sending a POST request as GET. Switch the GET to POST, or include the searched term in the URL and remove the Request $request part of your search(Request $request) function since GET will not provide an instance of Request. Just make it search($terms) instead if you go that route. I would personally just switch to POST though.
IE:
Route::post('/article/show', 'HomeController#search');
{!! Form::open(['method'=>'POST', 'url'=>'/arti...
In your form add
{{ csrf_token() }}
Also you will want to check if 'search' has a value, so wrap it around a if ($request->search)
Also, it looks like you may have a SQL error somewhere else on the page which is cause this.
check your table name, or try this
public function search(Request $request)
{
$cari = $request->get('search');
$data['result']= DB::table('articles')->WHERE('title', 'LIKE', '%' .$cari . '%')->paginate(10);
return view('/article/show', $data);
}
your form
<form class="navbar-form navbar-left" method="GET" action="{{url('search')}}">
<div class="input-group">
<input type="text" class="form-control" placeholder="Search" name="search">
<button class="btn btn-default" type="submit">
<i class="fa fa-search"></i>
</button>
</div>
</form>

Getting TokenMismatchException in VerifyCsrfToken.php line 53 in Laravel 5.1 while using csrf token

I am getting TokenMismatchException in VerifyCsrfToken.php line 53:
I am using {!!Form::open()!!}
{!!Form::close!!}. When I click the add Button in my form with empty field for the first time, it shows me error as I set the validation rule. But when I click the Add button again without refreshing the page, it shows me the TokenMismatchException error. I have checked with dd() and it shows me the token like this:
array:3 [▼
"_token" => "5dXwRHbz4GNY1tx9OVeWPcOkirVIm0YtpkZufFbr"
"menu_name" => ""
"menu_price" => ""
Here is my form code:
{!! Form::open(array('route' =>'upcoming.store', 'method'=>'POST')) !!}
<div class="col-lg-6 col-sm-offset-3 top-spacing">
<input type="text" name="menu_name" placeholder="Menu Name.." class="form-control">
</div>
<div class="col-lg-6 col-sm-offset-3 top-spacing">
<input type="text" name="menu_price" placeholder="Menu Price.." class="form-control">
</div>
<div class="col-sm-2 col-sm-offset-8 top-spacing">
<button class="btn btn-success">
Add +
</button>
</div>
</div>
{!! Form::close() !!}
Here is my controller store function:
public function store(Request $request)
{
dd($request->all());
$this->validate($request, array(
'menu_name'=>'required',
'menu_price'=>'required',
));
$upcoming = new Upcomingfood;
$upcoming->menu_name=$request->menu_name;
$upcoming->menu_price=$request->menu_price;
$upcoming->save();
Session::flash('success','Food Menu Added Successfullly');
return redirect()->back();
}
Can anyone help?
I have solved this problem by going to
`VerifyCsrfToken.php`
and then I have changed
throw new TokenMismatchException;
by
else{
return redirect()->back();
}
But I am not sure am I right or wrong to apply this way. will it bring any problem in my future work in this project. anyone please make me sure. please.
Try add {{ csrf_field() }} inside the form.
I really recommend that you read official documentation https://laravel.com/docs/5.4/csrf

Resources