search query not working in laravel - php

I need to return the results of what the user write in the search bar, but when i press search to test it nothing happens.
this is how i created the search bar
<form class="form-inline" role="search" action="{{ route('search-source') }}" method="POST">
{{ csrf_field() }}
<div class="form-group">
<input type="text" class="form-control" name="searchbar" placeholder="Find a source!">
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
in my controller i have the following code to find what the user has entered in the search bar. It searches the datebase for a title thats like whats written in the search bar. If nothing is found it return's an error (this is working).
if a row higher than 0 return it need to bring that result back to the page
public function searchSource(Request $request){
$this->validate($request,[
'searchbar' => 'required',
]);
$find = $request['searchbar'];
$query = Source::where('title','LIKE', '%'.$find.'%')->where('user_id', Auth::user()->id)->get();
if(count($query) > 0) {
return redirect()->route('sources-index')->with(['query' => $query]);
}else{
return redirect()->route('sources-index')->with('customerror', 'nothing found, try a different searchterm.');
}
}
back on the page it need to get the result if there is asked for a searchterm, else it need to give everything of the database
#if(!empty($query))
#foreach($query as $querys)
<tr>
<td class="source-cell">
{{$querys->title}}
</td>
<td>
{{$querys->summary}}
</td>
<td>
{{$querys->course->name}}
</td>
</tr>
#endforeach
#else
#foreach ($sources as $source)
<tr>
<td class="source-cell">
{{$source->title}}
</td>
<td>
{{$source->summary}}
</td>
<td>
{{$source->course->name}}
</td>
</tr>
#endforeach
#endif
I tried dd() on a couple of places and everything worked fine, except on the page, i tried dd($query) after the if statement nothing happend.
I tried it after the foreach nothing happend.
But when i tried it before the if statement i got an error
Undefined variable: query (View:
...\resources\views\sources\index.blade.php)
What am i doing wrong.

In your above code $query is misspelled
Change
#if(!empty($uery))
to
#if(!empty($query))
Modify your controller like below :
public function searchSource(Request $request){
$this->validate($request,[
'searchbar' => 'required',
]);
$find = $request['searchbar'];
$query = Source::where('title','LIKE', '%'.$find.'%')->where('user_id', Auth::user()->id)->get();
return redirect()->route('sources-index')->with(['query' => $query]);
}
Modify your view like below :
#if(!empty($uery))
#foreach($query as $querys)
<tr>
<td class="source-cell">
{{$querys->title}}
</td>
<td>
{{$querys->summary}}
</td>
<td>
{{$querys->course->name}}
</td>
</tr>
#endforeach
#else
nothing found, try a different searchterm.
#endif
#if(!empty($sources))
#foreach ($sources as $source)
<tr>
<td class="source-cell">
{{$source->title}}
</td>
<td>
{{$source->summary}}
</td>
<td>
{{$source->course->name}}
</td>
</tr>
#endforeach
#else
nothing found, try a different searchterm.
#endif
Because in your else part redirection does not have $query variable.

redirect()->with() uses session to store the data, so you'll need to change the code to:
#if (session()->has('query'))
#foreach(session('query') as $querys)
Or, you need to change redirect() part to this:
return view('query.index', compact('query'));

# Peter Arents Could you please try as below
$query = Source::where('title', 'LIKE', "%$find%")->where('user_id', '=', Auth::user()->id);

Related

Bulk updating, update multiple rows in laravel

Am trying to update multiple data in laravel but the solutions am getting when i search on goole are not what am lookin for. here is mycode:
In blade
<form action="{{url('users/update')}}" method='post'>
#foreach($data as $users)
<tr>
<td>
<input type="" name="id[]" value="{{ $users->id }}">
<input type="" name="names[]" value="{{ $users->name }}">
</td>
</tr>
#endforeach
<button type="submit">Submit</button>
</form>
In Controller
public function updateuser(Request $request){
$users = user::where("id" ,$request->$id)->update(["name" => $request->names]);
return back()->with('success','Successfully');
}
I want to be able to update lets say i have 10 records in the database i want to update all 10 using their respective IDs
Thank you in advance
First if you want to update or do something you need to provide #csrf in the form. If you are doing update or delete method you need to provide #method('PUT') or #method('DELETE').
Second thing I am not sure that you can provide user::, try User::.
Here is what you asked for
foreach($request->id as $key => $id) {
User::where('id', $id)->first()->update([
'name' => $request->names[$key]
]);
}
This should work fine :)

I need to fetch my pivot values from many to many relationship data

I have done much research about this but I can't fetch the pivot table as I want.
I want to just fetch the measurement value from the pivot table-like structure you can see. Please check my all details first then you know what I want to show.
Model MeasurementPart.php
public function customers(){
return $this->belongsToMany(Customer::class, 'customer_measurements', 'measurementpart_id', 'customer_id')->withPivot('measurement');
}
Model Customer.php
public function measurementparts(){
return $this->belongsToMany(MeasurementPart::class, 'customer_measurements', 'customer_id', 'measurementpart_id')->withPivot('measurement');
}
Model CustomerMeasurement.php
public function customers(){
return $this->belongsToMany(Customer::class);
}
public function measurementparts(){
return $this->belongsToMany(MeasurementPart::class);
}
Here is my controller CustomerMeasurementController.php
public function editMeasurements(Request $request, $id){
$customer = Customer::with("measurementparts")->find($id);
$clothType = ClothType::all();
return view('customerMeasurements.edit', compact('customer', 'clothType'));
}
public function updateMeasurements(Request $request, Customer $customer){
$measurements = $request->input('measurement');
$filteredmeasurements = array_filter($measurements, function($a){
return $a !== null;
});
$measurement_id = $request->input('measurement_id');
$result = array_combine($measurement_id, $measurements);
$syncData = array();
foreach($result as $measurement_id=> $filteredmeasurements){
$syncData[$measurement_id] = array('measurement' => $filteredmeasurements);
}
$customer->measurementparts()->sync($syncData);
return redirect()->route('customers.index')->withStatus(__('Measurements successfully Updated.'));
}
View EditMeasurements.blade.php
<form action="{{ route('updateMeasurements', ['customer'=> $customer]) }}" method="POST">
#csrf
#foreach ($clothType as $item)
<tr>
<h3>{{ $item->name }}</h3>
<table>
#foreach ($item->measurementparts as $part)
<tr>
<td>
<img style="width: 191px;" class="img"
src="{{ asset('storage/image/' . $part->image) }}" alt="">
<input type="hidden" name="measurement_id[]" value="{{$part->id}}">
</td>
<td>{{ $part->name }}</td>
<td><input type="text" name="measurement[]" value="**I want to put here my measurment value**" class="form-control"></td>
</tr>
#endforeach
</table>
</tr>
<br>
<hr>
#endforeach
<input type="submit" value="Submit" class="btn btn-primary">
</form>
this is the image where I want to put
enter image description here

How do I specify page to display at the beginning in controller

I have a paginate like :
//Controller (UserController)
public show(){
$users = DB::table('user')->paginate(15);
return view('user');
}
public process(Request $request){
//something update
return $this->show();
}
//View (user.blade.php)
<head>
<script>
//submit user's id and name to UserController#process
</script>
</head>
<body>
{{ $users->link() }}
<table>
<thead>
<tr>
<th>userName</th>
<th>modifly</th>
</tr>
</thead>
<tbody>
#foreach($users as $user)
<tr>
<td><input type="text" value="{{ $user->name }}"</td>
<td><input type="submit" value="modifly"></td>
</tr>
#endforeach
</tbody>
</table>
</body>
When I submit a request at 3rd page , It will show 1st page just like I view('user') at first , but I need show the currentPage page after I submit.
How do I pass 3rd page($users->currentPage()) to DB::table('user')->paginate(15) and view('user') with currentPage when I submit a request at 3rd page?
in your submit action pass currentpage as queryparameter, then in your controller,
$page=$request->input('queryname');
// do update here
return redirect('/your/url?page='.$page);
use return redirect instead return $this->show();
Submit the page number in the form for example as follows:
//Controller (UserController)
public show(Request $request){
$returnValues = array();
$users = DB::table('user')->paginate(15);
$returnValues['users'] = $users;
$returnValues['page'] = 1;
if ($request->has('page'))
$returnValues['page'] = $request->input('page');
return view('user', $returnValues);
}
public process(Request $request){
//something update
return $this->show($request);
}
//View (user.blade.php)
<head>
<script>
$('#pagesContainer a').on('click',function () {
var page = $(this).attr("href").split('page=')[1];
$('#pageNumber').val(page);
$('input[type=submit]').click();
return false;
})
</script>
</head>
<body>
<div id="pagesContainer">
{{ $users->link() }}
</div>
<table>
<thead>
<tr>
<th>userName</th>
<th>modifly</th>
</tr>
</thead>
<tbody>
#foreach($users as $user)
<tr>
<td><input type="text" value="{{ $user->name }}"</td>
<td>
<input type="hidden" name="page" id="pageNumber" value="{{ $page }}">
<input type="submit" value="modifly">
</td>
</tr>
#endforeach
</tbody>
</table>
</body>
However, depending on the number of forms on your page, it may require a little bit of changes

Laravel destroy function always delete the record with lowest id

im new to laravel. So im trying to delete a record from database from my index page. But it only delete the record with the lowest primary key value, my id field.
Here's my controller code for destroy function:
public function destroy(Province $province)
{
//
$findProvince = DB::table('provinces')->where('id', $province->id)->delete();
if($findProvince){
return redirect()->route('provinces.index')->with('success', 'Province deleted successfully');
}
return back()->with('error', 'Province could not be deleted');
//var_dump($province->id);
}
Here's my view code:
#extends('layouts.app')
#section('content')
<div class="col-md-8 offset-md-2">
<br/>
<div>
Add New Province
</div>
<br/>
<table class="table">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">Name</th>
<th scope="col">Image</th>
<th scope="col">Operations</th>
</tr>
</thead>
<tbody>
#foreach($provinces as $province)
<tr>
<th scope="row">{{ $province->id }}</th>
<td>{{ $province->name }}</td>
<td><img src="../{{ $province->imgPath }}" width="200px"/></td>
<td>
Edit |
<a
class="btn btn-danger"
href="#"
onclick="
var result = confirm('Are you sure you wish to delete this province?');
if( result ){
event.preventDefault();
document.getElementById('delete-form').submit();
}
">Delete
</a>
<form id="delete-form" action="{{route('provinces.destroy', $province->id)}}" method="POST" style="display: none;">
<input type="hidden" name="_method" value="delete">
{{ csrf_field() }}
</form>
</td>
</tr>
#endforeach
</tbody>
</table>
</div>
#endsection
I tried using var_dump on the $province->id but it only output the lowest 'id' value.
id's are unique. You will get this unexpected behavior if you use the same id in a loop. Either use unique id's or put your buttons inside the form (I suggest this).
<td>
<form class="delete-form" action="{{ route('provinces.destroy', $province->id) }}" method="POST">
<input type="hidden" name="_method" value="delete">
{{ csrf_field() }}
Edit |
<a class="btn btn-danger">Delete</a>
</form>
</td>
And then use this Javascript in a seperate file for confirmation:
(function(){
let forms = document.querySelectorAll('form.delete-form');
[].forEach.call(forms, function(form){
form.onsubmit = function(e) {
if ( ! confirm('Are you sure you wish to delete this province?'))
return e.preventDefault();
}
});
})();
If you still want to use your approach, add the id of $province to the id attribute of your form. This will make your form unique so you get access it with an id.
<form id="delete-form-{{ $province->id }}" ...>
And then your Javascript:
if( result ){
event.preventDefault();
document.getElementById('delete-form-{{ $province->id }}').submit();
}
Thanks everyone for your help. And sorry that it took me long to reply. I've been really busy with other schools. So i managed to track down the problem with my code. It's with my view. All the created delete form has the same id. So if i just added the record id to the form. It works just fine.

How to pass form data to another page in Laravel

I need some help in my laravel application with passing the values from a form though to another page. I have a table with data on area objects, and I want to be able to select two (or more) area objects, and then view those in a new page.
In my index.blade.php I have the hollowing form:
<form method = "POST" action="/areas/comparison" id="preferencesForm" class="form-group">
!{csrf_field()}!
<table id='areas_table' class="table table-striped">
<thead class="thead-default">
<tr>
<th>Select</th>
<th>Area</th>
<th>Overall Score</th>
<th>Housing Affordability Ratio</th>
<th>Mean House Price</th>
<th>Crime Level</th>
<th>Green Space</th>
<th>Good GCSE's</th>
<th>Number of Pubs & Restaraunts:</th>
<th>Superfast Broadband</th>
</tr>
</thead>
<tbody>
#foreach ($areas as $area)
<tr>
<td scrope="row"><input type="checkbox" name="area[]" value="!{$area->id}!"></td>
<th>!{$area->name}!</th>
<td>!{Helpers::calculateOverallScore($area)}!</td>
<td>!{$area->housing_affordability_ratio}!</td>
<td>£!{$area->mean_house_price_2015}!</td>
<td>!{$area->crime}!</td>
<td>!{$area->greenspace*100}!%</td>
<td>!{$area->five_good_gcses*100}!%</td>
<td>!{$area->restaurants}!/km<sup>2</sup></td>
<td>!{$area->superfast_broadband*100}!%</td>
</tr>
#endforeach
#endif
</tbody>
</table>
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<input type="submit" id="compare_button" class="btn btn-primary" value="Compare"/>
</form>
And I would like to then go to show_comparison.blade.php and be able to display the data on the two (or more) areas that I selected.
In routes.php I have:
Route::post('/areas/comparison', 'AreasController#show_comparison');
And then in AreasController:
public function show_comparison(Area $area)
{
$formData = Request::all(); //Get the form data with the facade
return view('areas.show_comparison', compact('formData'));
}
However when I click submit and it tries taking me to show_comparison.blade.php it returns the error message "Trying to get property of non-object".
Here is show_comparison.blade.php:
#extends('layout')
#section('content')
<div class="container">
Back
<h1>Comparison</h1>
<p>Hello, this is the comparison page. !{$formData}!</p>
</div>
#stop
Ideally I would like to be able to print the data in the form of !{ area1->name}! and !{area2->name}! according to my selection.
If anyone can show my how I should be passing form selected data through to another page that would be amazing. (Thank you for taking the time to read this.)
I was given an answer on another forum. This solution will take the id that the form passes it, then will fetch the corresponding area objects and pass these in an array to the show_comparisons.blade.php view.
public function show_comparison(Request $request)
{
$areas= Area::whereIn('id',$request->area)->get();
return view('areas.show_comparison', compact('areas'));
}

Categories