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
Related
I have two functions - 1 showing the results and 1 to download results that are on page.
The problem is that I can't find a way how to download only the results. Instead when I hit Download button it downloads all records in database.
This is what I have in my controler
public function index(Request $request)
{
$user = DB::table('downloads')
->select('user_id as downloader_id', DB::raw('COUNT(id) as count'))
->groupBy('user_id');
if(isset($request->startDate) && isset($request->dateEnd)) {
$user = $user->whereBetween(DB::raw("DATE_FORMAT(downloads.created_at, '%Y-%m-%d')"), [$request->startDate, $request->dateEnd]);
} elseif (isset($request->startDate)) {
$user = $user->where('created_at',$request->startDate);
}
$works=DB::table('users')
->joinSub($user, 'downloads_byuser', function ($join) {
$join->on('id', '=', 'downloads_byuser.downloader_id');
})
->select('users.id as user_id', 'users.name as name', 'users.email as email', 'count')
->get();
return view('admin.downloadsuser', compact("works"));
}
public function download(Request $request){
$headers = array(
// some headers
);
//creating the download file
$filename = public_path("Downloads.csv");
$handle = fopen($filename, 'w');
//adding the first row
fputcsv($handle, [
"Email",
"Downlaods",
]);
//adding the data from the array
foreach ($works as $each_user) {
fputcsv($handle, [
$each_user->email,
$each_user->count,
]);
}
fclose($handle);
return Response::download($filename, "Downloads.csv", $headers);
}
And this is in the blade
<form>
<input type="date" name="startDate" id="startDate">
<input type="date" name="dateEnd" id="dateEnd">
<button type="submit" class="btn btn-primary"> Filter </button>
</form>
<form action="{{ route('admin.works.download') }}">
<button type="submit" class="btn btn-primary"> Download </button>
</form>
<table class="table">
<thead>
<tr>
<th>User</th>
<th>Email</th>
<th>Downloads</th>
</tr>
</thead>
<tbody>
#foreach($works as $work)
<tr>
<td>{{ $work->name }}</td>
<td>{{ $work->email }}</td>
<td>{{ $work->count }}</td>
</tr>
#endforeach
</tbody>
</table>
Any help is appreciated.
Store the date when the search criteria are provided in the session, like this
\Session::put('startDate', $request->startDate);
\Session::put('dateEnd', $request->dateEnd);
After that in your download function retrieve the session dates. If none exists, the second parameter is returned instead.
$startDate = Session::get('startDate', '2022-02-11');
$dateEnd = Session::get('dateEnd', '2022-02-11');
You could just make them null, and have your query scope ignore them - which is essentially making the default export return all-time (unfiltered) records.
$startDate = Session::get('startDate', null);
$dateEnd = Session::get('dateEnd', null);
Or use carbon and return current date as default - \Carbon\Carbon::parse()
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
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.
I`m developing attendance management system.
My view is like this.
What I need is if I select the time value and press Mark here button current data and time value need to be stored in the database according to trainee ID.
Here is the view for that .
<table class="table table-striped">
<thead>
<th>Trainee ID</th>
<th>Name with Initials</th>
<th>Time</th>
<th>Mark Here!</th>
</thead>
<tbody>
#foreach($items as $item)
<tr>
<td>
<div class="form-group">
<input type="text" name="trainee_id" class="form-control" value="{{ $item->trainee_id }}">
</div>
</td>
<td>
{{ $item->name_with_initials }}
</td>
<td>
<label><input type="checkbox" name="time" id="time" value="time"> Time</label>
</td>
<td>
<a class="btn btn-info" href="Bankdetails/{{ $item->trainee_id }}">Mark Here</a>
</td>
</tr>
#endforeach
</tbody>
</table>
I know that my Controller is perfectly alright and need to be fixed.
public function store(Request $request)
{
$queryType = $request->time;
$carbon = new Carbon('queryType');
attendancedetails::create($request->all());
return view('traineeattendance.attendanceo');
}
Here is the necessary data model .
class attendancedetails extends Model
{
protected $table = "attendancedetails";
protected $fillable = ['id',
'attendance_date',
'trainee_id',
'name',
'starting_time',
'end_time',
'site_visit_time'];
}
Can anyone suggest me to get fixed this.
You already have the current time by default in laravel. When you save a record in migrations there is a timestamps(); input:
public function up()
{
Schema::create('users', function (Blueprint $table) {
...
$table->timestamps();
});
}
That creates a created_at and updated_at column in your DB table! And you can use created_at time when that input is saved to show it elsewhere!
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);