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()
Related
I am trying to save this "code" attributes into my codes table along with the "gift_card_id", but only the first one is saved.
When I call the dd($giftCard), it shows me the model info itself, not
an object from it. and when I dd($giftCard->id), it gives me null.
When I add ($id) to my function parameters "public function generateCodes(Request $request, GiftCard $giftCard, $id)", and change the create function to "$giftCard->codes()->create(['code' => $code, 'gift_card_id' => $id]);"
and call dd($id), it shows the right id.
In both of the above, the data get stored excpt the "gift_card_id".
web.php
Route::post('gift-cards/{giftcard}/add-codes', 'GiftCardController#generateCodes')->name('gift-cards.generateCodes');
GiftCardController.php
public function generateCodes(Request $request, GiftCard $giftCard) {
$request->validate([
'amount' => 'required|integer|min:1',
]);
if ($request->input('amount') > 0) {
do {
$codes = [];
for ($i = 0; $i < $request->input('amount'); $i++) {
$codes[] = (string)mt_rand(pow(10, 10), pow(10, 11) - 1);
}
$codesUnique = Code::whereIn('code', $codes)->count() == 0;
} while (!$codesUnique);
foreach ($codes as $code) {
// dd($id);
$giftCard->codes()->create(['code' => $code]);
}
}
View.blade.php
#foreach($giftCards as $key => $giftcard)
<tr data-entry-id="{{ $giftcard->id }}">
<td> {{ $giftcard->name ?? '' }} </td>
<td> {{ $giftcard->price ?? '' }} </td>
<td> {{ $giftcard->codes_count ?? '' }} </td>
#can('gift_card_create')
<td>
<form action="{{route('gift-cards.generateCodes', $giftcard->id)}}" method="POST">
#csrf
<input type="number" class="form-control" name="amount" placeholder="Amount" required>
<input type="submit" class="btn btn-xs btn-success ml-2" value="Generate">
</form>
</td>
#endcan
</tr>
#endforeach
You need to have the type-hinted parameter name on the route action match the name of the route parameter if you want Explicit Route Model Binding to take place. If you don't match these you are just defining dependencies that the method needs which would cause Dependency Injection to happen. You can change the route parameter name or the name of the parameter for the method so they match:
Route::post('gift-cards/{giftCard}/add-codes', ...);
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
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
I have an index page where I list all the data that I have and there is also a simple filtering form that makes a POST request to its given route
#section('content')
<h4>Maçlar</h4>
<form class="form-inline" method="post" action="{{ route('games.filter') }}">
{{ csrf_field() }}
<div class="form-group mb-2">
<label class="sr-only">Email</label>
<select class="form-control" id="season-select" name="season">
<option value="0">Tüm Sezonlar</option>
#foreach ($seasons as $season)
<option value="{{$season->id}}" {{old('season') == $season->id ? 'selected' : ''}}>{{$season->season}}</option>
#endforeach
</select>
</div>
<div class="form-group mx-sm-3 mb-2">
<label for="week-select" class="sr-only">Password</label>
<select class="form-control" id="week-select" name="week">
<option value="0">Tüm Haftalar</option>
#foreach ($weeks as $week)
<option value="{{$week->id}}" {{old('week') == $week->id ? 'selected' : ''}}>{{$week->week}}</option>
#endforeach
</select>
</div>
<button type="submit" class="btn btn-primary mb-2">Filtrele</button>
</form>
<table class="table table-striped">
<thead>
<tr>
<th scope="col">Sezon</th>
<th scope="col">Hafta</th>
<th scope="col">Ev Sahibi Takım</th>
<th scope="col">Misafir Takım</th>
<th scope="col">Tarih ve Saat</th>
<th scope="col">Yer</th>
</tr>
</thead>
<tbody>
#foreach ($games as $game)
<tr>
<td>{{$game->season->season}}</td>
<td>{{$game->week->week}}</td>
<td>{{#$game->homeTeam->name}}</td>
<td>{{#$game->awayTeam->name}}</td>
<td>{{#$game->game_date_time}}</td>
<td>{{#$game->place}}</td>
</tr>
#endforeach
</tbody>
</table>
#endsection
And in the controller my index method is as below
public function index()
{
$seasons = Season::all();
$weeks = Week::all();
$games = Game::with('season', 'week', 'homeTeam', 'awayTeam')->get();
return view('game.index')->with(compact('games', 'seasons', 'weeks'));
}
And there is also my filter method which performs POST request and passes filtered data to same view as index uses.
public function filter(Request $request)
{
$seasons = Season::all();
$weeks = Week::all();
$games = Game::with('season', 'week', 'homeTeam', 'awayTeam')
->when(request('season') != 0, function ($q) {
return $q->where('season_id', request('season'));
})->when(request('week') != 0, function ($q) {
return $q->where('week_id', request('week'));
})
->get();
return view('game.index')->with(compact('games', 'seasons', 'weeks'));
}
What I want to learn is, what is the best way of implementing such a case ? Is it possible to redirect back to same index route after performing POST request for filtering ? And old method does not work in the blade template so I can not display old form data after the request. What can be the problem with it ? Lastly, how can I remove these duplicate rows in the index and filter methods.
$seasons = Season::all();
$weeks = Week::all();
Any help would be appreciated. PS: I do not want to use Ajax, Vue.js etc. I want to do it with Laravel.
You can also use filter in index method. No need to create another method for filter.
change in view.
<form class="form-inline" method="post" action="{{ route('games.index') }}"> // form redirect to index method
change in index method.
public function index(Request $request)
{
$seasons = Season::all();
$weeks = Week::all();
if($request->has('season') && $request->has('week') ){ // check filter value is passed or not
$games = Game::with('season', 'week', 'homeTeam', 'awayTeam')
->when(request('season') != 0, function ($q) {
return $q->where('season_id', request('season'));
})->when(request('week') != 0, function ($q) {
return $q->where('week_id', request('week'));
})
->get();
}
else{
$games = Game::with('season', 'week', 'homeTeam', 'awayTeam')->get();
}
return view('game.index')->with(compact('games', 'seasons', 'weeks'));
}
i have code with laravel 5.4
i wanna show data from database with filter date...
how it's work? can help me?
view.blade.php
database
and this's my code in view.blade.php
<div class="table-responsive">
<table class="table table-striped table-hover table-condensed">
<thead>
<tr>
<th><strong>No</strong></th>
<th><strong>Nama</strong></th>
<th><strong>Alamat</strong></th>
<th><strong>Lokasi</strong></th>
<th><strong>Tanaman</strong></th>
<th><strong>Jumlah Panen</strong></th>
<th><strong>Luas Lahan</strong></th>
</tr>
</thead>
<tbody>
#foreach($hasil as $key => $data)
<tr>
<th>{{$no++}}</th>
<th>{{$data->nama_user}}</th>
<th>{{$data->alamat}}</th>
<th>{{$data->id_lokasi}}</th>
<th>{{$data->nama_tanaman}}</th>
<th>{{$data->jumlah_panen}}</th>
<th>{{$data->luas_lahan_panen}} HA</th>
</tr>
#endforeach
</tbody>
</table>
</div>
<div class="col-sm-3">
<div class="box">
<div class="box-header with-border">
<h3 class="box-title">Filter</h3>
<p>Pilih Tanggal : {!! Form::input('month', 'published_at', null, ['class' => 'form-control']) !!}</p>
<button name="filter" class="btn btn-primary form-control" id="filter" onclick="filter">Pilih Tanggal</button>
</div>
</div>
</div>
and this's the code from web.php (route)
Route::get('laporhasil', function () {
$hasil = DB::select("SELECT `tbl_user`.`nama_user`, `tbl_user`.`alamat`, `tbl_lapor_hasil`.`id_lokasi`, `tbl_tanaman`.`nama_tanaman`, `tbl_lapor_hasil`.`luas_lahan_panen`,`tbl_lapor_hasil`.`jumlah_panen`FROM `tbl_lapor_hasil` INNER JOIN `tbl_user` ON `tbl_lapor_hasil`.`id_user` = `tbl_user`.`id_user` INNER JOIN `tbl_tanaman` ON `tbl_lapor_hasil`.`id_tanaman` = `tbl_tanaman`.`id_tanaman`");
$no = 1;
return view('laporhasil', ['hasil' => $hasil], ['no' => $no]);
});
If you want to get all data which are created today then you then you can follow this code snippet-
$data = Modelname::whereDate('created_at','=',\Carbon\Carbon::now())->get();
//Assuming you have a date field named `created_at`
If you want to get data by specific day then -
$data = Modelname::whereDay('created_at','=',$day)->get();
Same way you can get data by month or year.
$data = Modelname::whereMonth('created_at','=',$month)->get();
$data = Modelname::whereYear('created_at','=',$year)->get();
The $day, $month, $year represents day, month and year value respectively.
Make a filter form with get method and same route in the action as the route view.blade.php.
i.e. if your route of view.blade.php is my-data then make a filter form like
<form action="{{route('my-data')}}" method="GET">
<input type="text" name="date" class="some-class" />
<input type="submit" value="Filter" />
</form>
And the method of the route my-data like -
public function myData(Request $request){
$model = new Mymodel(); // This is you model name of the corresponding table
if(!empty($request->date)){
$model = $model->whereDate('date','=', $request->date);
}
if(empty($request->date)){
$result = Mymodel::all();
}else{
$result = $model->get();
}
return view('view', compact('result'));
}
This method checks if the request has date field and it's value or not. If it finds date field then fetch the data from Mymodel. Careful about not to use ->get(). Finally check if the request has no date field then request all the data you want to fetch from Mymodel otherwise get the filtered data to your view.