how to search in a collection laravel? - php

i have 3 tables , arts(code,designation,prix,qte,gamme_id)
gammes(type)
factures(art_id,prix_total,quantité)
i want to search all gammes between 2 dates in facture table but the problem i dont have relation between factures and gammes , i just have relation between factures and arts
controller
public function store(Request $request)
{
$prix_totale=0;
$Gammes = Gamme::all();
$gamme_id=$request->get('gamme_id');
$date_debut=$request->get('date_debut');
$date_fin=$request->get('date_fin');
$articles=Art::where('gamme_id','LIKE',$gamme_id)->paginate(1000);
$data =Facture::where('art_id','LIKE',$articles)->whereBetween('created_at',[$date_debut,$date_fin])->orderByDesc('created_at')->paginate(1000);
foreach ($data as $p) {
$prix_totale+=$p->prix;
}
return view('affairegamme.resultat', compact('data','arts','prix_totale','articles'));
}
index.blade.php
<form method="post" action="{{ route('affairegamme.store') }}" enctype="multipart/form-data" width="20" height="20">
#csrf
<div class="form-group">
<label class="col-md-4">Gamme:</label>
<div class="col-md-8">
<select name="gamme_id" id="gamme_id" class="form-control" >
<option value="">Select Gamme</option>
#foreach($gammes as $gamme)
<option value="{{ $gamme->id}}">{{ $gamme->type }}</option>
#endforeach
</select>
</div>
</div>
<div class="form-group">
<label class="col-md-4">Date debut :</label>
<div class="col-md-8">
<input type="date" name="date_debut" value="{{ old('date', date('Y-m-d')) }}" class="form-control input-lg" />
</div>
</div>
<div class="form-group">
<label class="col-md-4">Date fin</label>
<div class="col-md-8">
<input type="date" name="date_fin" value="{{ old('date', date('Y-m-d')) }}" class="form-control input-lg" />
</div>
</div>
<br/>
<div class="form-group text-center">
<input type="submit" name="add" class="btn btn-primary input-lg" value="Chercher !" />
</div>
</form>
resultat.blade.php
<table class="table table-bordered table-striped">
<td><h6>ID de facture</h6></td>
<td><h6>date</h6></td>
<td><h6>Operation_id</h4></td>
<td><h6>Article</h4></td>
<td><h6>Prix Unitaire d Article</h4></td>
<td><h6>Quantite</h6></td>
<td><h6>Prix Totale</h6></td>
</tr>
#foreach($data as $row)
<tr>
<td>{{ $row->id}}</td>
<td>{{ $row->created_at}}</td>
<td>{{ $row->operation_id }}</td>
<td> {{$row->art->designation}}</td>
<td> {{$row->art->prix}}</td>
<td> {{$row->qte}}</td>
<td> {{$row->prix}}</td>
#endforeach
</table>
<br> </br>
<h1 style="font-size:200% ;text-align:center">Le chiffre d affaire pour la gamme est : {{$prix_totale}} dt</h1>

The below provided eloquent query will search for the fractures between the provided dates in the fracture table.
$grammesBetweenTwoDates = Gramme::whereHas('arts',function($query) use ($date_debut,$date_fin) {
// Any query to apply filter in arts
return $query->whereHas('fractures', function($fractureQuery) use ($date_debut,$date_fin){
// Any query to apply filter in fractures
return $fractureQuery->whereBetween('created_at', [$date_debut,$date_fin]);
});
})->paginate(1000);
Since you seem to have problem understanding the answer I will try my best to explain. The above query instructs the database to
Find all the grammes that have arts (from grames_id present in arts table ).
Find all the arts that have fractures (from arts_id present in fractures table )
Find all the fractures that are in between two dates ( from the date provided in eloquent query )
When above all cases match the query return the result.
In the above query you need to have arts relation in Grammes model.
public function arts()
{
return $this->hasMany(Arts::class);
}
And you need to gave fractures relation in Art model
public function fractures()
{
return $this->hasMany(Fracture::class);
}

Related

How do i check if database row exist in laravel?

Hello how do i check if database row insert exist in laravel? i want to display something entries if > 0 and i want to display else if entries = 0. but i don t know how to do that. i tried with forelse, if else and i got same error. Undefined variable $istProj.
<div class="card-body">
#if ($istoric->isEmpty())
#forelse ($istoric as $istProj)
<div class="mb-3">
<table class='table'>
<tr class="table-row-heads">
<th>Id Proiect</th>
<th>Tip actiune </th>
<th>Colaborator </th>
<th>Suma </th>
<th>Data </th>
</tr>
<tr class="table-row-data">
<td>{{ $istProj->id_proiect }}</td>
<td>{{ $istProj->action_type }}</td>
<td>{{ $istProj->colaborator_id }}</td>
<td>{{ $istProj->suma }}</td>
<td>{{ $istProj->data }}</td>
</tr>
</table>
</div>
#empty
<div class="card-body">
<h1>Nu au fost gasite inregistrari</h1>
</div>
#endforelse
#endif
</div>
<form action="{{ url('/') }}" method="POST">
#csrf
#method('PUT')
<div class="mb-3">
<label class="form-label">Id proiect</label>
<input type="text" class='form-control' value="{{ $proiecte->id }}" name='id_proiect' id='id_proiect' placeholder="Id proiect">
</div>
<div class="mb-3">
<label class="form-label">Tip actiune</label>
<select class="form-select" aria-label="Default select example" name='Status_Tranzactii'>
<option selected>Alege tipul actiunii (0 = cheltuiala, 1 = plata, 2 = incasare)</option>
<option value="cheltuiala">0</option>
<option value="plata">1</option>
<option value="incasare">2</option>
</select>
</div>
<div class="mb-3">
<label class="form-label">Colaborator</label>
<select class="form-select" aria-label="Default select example" name="Colab_id">
<option selected>Alege colaboratorul (daca este cazul)</option>
#foreach ($colaborator as $colaboratori)
<option value="{{ $colaboratori->id }}">{{ $colaboratori->id }} </option>
#endforeach
</select>
</div>
<div class="mb-3">
<label class="form-label">Suma</label>
<input type="text" class='form-control' value="{{ $istProj->suma }}" name='suma' placeholder="Introduceti suma">
</div>
<div class="mb-3">
<label class="form-label">Data</label>
<input type="text" class='form-control' value="{{ $istProj->data }}" name='data' placeholder="Introduceti data">
</div>
<button type='submit' class='btn btn-primary' style="float: right;">Adauga</button>
</form>
How can i make that to work?
Error on line with "Suma"
If I understand well, you already have a Collection result (From Eloquent or anywhere) and you need to do different action based on that result.
I'm,right? If yes....
To check the amount or entries you can use $result->count(), so in Blade you can:
#if($result->count() > 0)
Do something
#else
Do anotherthing
#endif

How to store an array as single row for each value in my database

the whole idea is that when a user click on checkbox and save, the form should be submitted with an array containing the checked values, and save them in the database as single row for each value. i don't know if this is possible but i'm sure you guys have a solution or can help me?
and here's my form:
<div class="">
<form style="width: 70%" method="POST" action="{{ URL('/admin/projects/services/save') }}"
enctype="multipart/form-data">
#csrf
<input type="hidden" name="id" id="id" value="{{ #$id }}">
<input type="hidden" name="projectid" id="projectid" value="{{ #$projectid }}">
<div class="row topSpacer">
<div class="col-3">
<p class="bold">Selected Services: <span class="red">*</span></p>
</div>
<div class="col-9">
<input type="text" id="selectedServices" name="selectedServices" value="" readonly>
</div>
</div>
<div class="row topSpacer">
<div class="col-3">
<p class="bold">Select a service: <span class="red">*</span></p>
</div>
<div class="col-9">
#foreach ($services as $service)
<input type="checkbox" name="service" value="<?php echo stripslashes($service->id); ?>">
<label for="service"><?php echo stripslashes($service->name); ?></label>
<br>
<hr>
#endforeach
#error('service')
<span class="text-danger">{{ $message }}</span>
#enderror
</div>
</div>
<div class="row topSpacerHuge">
<div class="col-12 textRight">
<button type="button"
onclick="window.location='{{ url('admin/projects/services/index/'.$projectid) }}'"
class="goBackBtn">Cancel</button>
<input class="saveBtn" id="saveBtn" type="submit" value="Save">
</div>
</div>
</form>
</div>
and my script to get checkboxes value:
<script>
$(function() {
$("input:checkbox[name='service']").click(function() {
$value = [];
$.each($("input:checkbox[name='service']:checked"), function() {
$value.push($(this).val());
$array = $value.join();
});
// console.log(value.join(", "));
$("#selectedServices").val($array);
})
});
</script>
for implementing checked values I recommend to use the select tag
and you can give A name attribute with [] and it will collect all of your data
for example , look at my project's file which I'm trying to collect name of some users :
<select name="users[]" id="example-with-maxHeight" class="multiselect-group" multiple >
#foreach($users as $user)
<option #if($user->average < $averageParticipate )class="alert-danger" #endif value="{{$user->id}}">{{$user->name}} - {{$user->average}}</option>
#endforeach
</select>
have attention to users[] in name attribute
now in your request you can access all of your checked items .
if we look at your code ,can be some thing like this :
<label for="service"><?php echo stripslashes($service->name); ?></label>
<select name="services[]" id="" class="multiselect-group" multiple >
#foreach($users as $user)
<option value = "{{$sevice->id}}"> <?php echo stripslashes($service->name); ?></option>
#endforeach
</select>
now in your controllers you can access them :
request->get('services');
it will give you back an array of selected items .
Notice that id attribute helps me to interact with my java script code
you can rename it to yourselves .

How do I add multiple data at once in Laravel?

I have a field gender, age-group and patient_type. I want to store count for each patient type with age-group and gender. This is my form formData. And this is array of data I get arrayData. Also multiple age-group can be added.
For example, age-group=0-1, new_patient=>male=10,Female=60, old_patient=>male=50, female=20. How can I store this form data for multiple age-groups.
My Form code
<div class="newAgeGroup mt-5" id="newAgeGroup_0">
<div class="form-group row">
<div class="col-md-2">
<label for="">Select Age Group</label>
</div>
<div class="col-md-5 mb-3">
<select name="age_id[]" class="form-control" id="">
<option value="">Select Age Group</option>
#foreach($ages as $age)
<option value="{{$age->id}}">{{$age->start_age}}
-{{$age->end_age}}</option>
#endforeach
</select>
</div>
<div class="col-md-5">
<button type="button" onclick="addAgeGroup();"
class="btn btn-primary rounded-0 float-right addAgeGroup">Add Age Group
</button>
</div>
</div>
<table class="table table-bordered">
<thead>
<tr>
<th></th>
#foreach($patient_types as $patient_type)
<th>
{{$patient_type->name}}
<input type="hidden" name="patient_type_id[]" value="{{ $patient_type->id }}">
</th>
#endforeach
</tr>
</thead>
<tbody>
#foreach($genders as $gender)
<tr>
<th>
{{$gender->name}}
<input type="hidden" name="gender_id[]" value="{{ $gender->id }}">
</th>
#foreach($patient_types as $patient_type)
<?php
$name =
"number_".$patient_type->id."_".$gender->id ;
?>
<td>
<input type="text" name="{{ $name }}[]" class="form-control">
</td>
#endforeach
</tr>
#endforeach
</tbody>
</table>
</div>
And this is what I have tried.
foreach ($request->input('age_id') as $key => $value) {
foreach ($request->input('patient_type_id') as $pt => $ptvalue) {
foreach ($request->input('gender_id') as $gkey => $gvalue) {
foreach ($request->input('number_'.$ptvalue.'_'.$gvalue) as $nkey => $nvalue) {
$report = new Report();
$report->admin_id = $this->admin()->id;
$report->category_id = $request->center_type;
$report->center_id = $request->center_id;
$report->dateTime = $request->dateTime;
$report->nationality = $request->nationality;
$report->type = 'OPD';
$report->age_id = collect($request->get('age_id')[$key])->implode(',');
$report->patient_type_id = collect($request->get('patient_type_id')[$pt])->implode(',');
$report->gender_id = collect($request->get('gender_id')[$gkey])->implode(',');
$report->number = collect($request->get('number_'.$ptvalue.'_'.$gvalue)[$nkey])->implode(',');
$report->save();
}
}
}
}
If I understand well, you want a single age group to have multiple records associated with it.
If that's the case I recommend you, to use relation in the database to achieve that.
For example these two tables:
Age group
age group attributes
id
id
age
age_group_id
gender
patient type
And when you save, the relationship will have you have counters and a better way to unite everything.
I hope this is useful to you.

Laravel Form displaying correct data but storing incorrect values in DB

I have come across a bug on my website and I am baffled as to how to fix it.. basically I have a view to create courses, I type a course title and secondly assign an instructor to that course and click save. But when i return to my index page.. the instructor i assigned is completely different. It appears there must be an issue with my select but I am not sure how to go about fixing it.. I am new to laravel so any help is greatly appreciated.
I have added a picture to try to further explain my issue, here i have selected an instructor -
And when i return to my index page, the newly created course 'test' has the admin user assigned... I am very confused -
create.blade.php
#extends('layouts.app')
#section('content')
<div class="row justify-content-center">
<div class="col-md-8">
<div class="card">
<div class="card-header">Create Course</div>
<div class="card-body">
<form method="POST" action="{{ route('admin.courses.store') }}" enctype="multipart/form-data">
#csrf
<div class="form-group">
<label class="required" for="name">Course Title</label>
<input class="form-control" type="text" name="title" id="id" value="{{ old('title', '') }}" required>
#if($errors->has('name'))
<div class="invalid-feedback">
{{ $errors->first('name') }}
</div>
#endif
</div>
<div class="form-group {{ $errors->has('instructors') ? 'has-error' : '' }}">
<label class="required" for="name">Instructors</label>
<select class="form-control select2" name="instructors[]" id="instructors" multiple>
#foreach($instructors as $id => $instructors)
<option value="{{ $id }}" {{ in_array($id, old('instructors', [])) ? 'selected' : '' }}>{{ $instructors }}</option>
#endforeach
</select>
</div>
<div class="form-group">
<button class="btn btn-danger" type="submit">
Save
</button>
</div>
</div>
</form>
</div>
</div>
#endsection
index.blade.php
#extends('layouts.app')
#section('content')
<div class="container">
<div class="row justify-content-center">
<div class="col-md-10">
<p>
#can('create_courses')
<button type="button" class="btn btn-success">Create Course</button>
#endcan('create_courses')
</p>
<div class="card">
<div class="card-header">Courses</div>
<div class="card-body">
<div class="table-responsive">
<table class="table">
<thead>
<tr>
<th>ID</th>
<th>Course Title</th>
<th>Instructor</th>
<th></th>
<th></th>
<th></th>
</tr>
</thead>
<tbody>
#foreach($course as $course)
<tr>
<th scope="row">{{ $course->id }}</th>
<td>{{ $course->title}}</td>
<td>{{ implode (', ', $course->instructors()->pluck('name')->toArray()) }}</td>
<td>
#can('edit_courses')
<a class="btn btn-xs btn-secondary" href="{{ route('admin.modules.index', $course->id) }}">
Modules
</a>
#endcan
</td>
<td>
#can('edit_courses')
<a class="btn btn-xs btn-primary" href="{{ route('admin.courses.edit', $course->id) }}">
Edit
</a>
#endcan
</td>
<td>
#can('delete_courses')
<form action="{{ route('admin.courses.destroy', $course->id) }}" method="POST" onsubmit="return confirm('Confirm delete?');" style="display: inline-block;">
<input type="hidden" name="_method" value="DELETE">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<input type="submit" class="btn btn-xs btn-danger" value="Delete">
</form>
#endcan
</td>
</tr>
#endforeach
</tbody>
</table>
</div>
</div>
</div>
</div>
<!-- <div class="col-md-2 col-lg-2">
<div class="list-unstyled">
Courses
Modules
</div>
</div> -->
</div>
</div>
#endsection
CoursesController;
<?php
namespace App\Http\Controllers\Admin;
use Gate;
use App\User;
use App\Course;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Input;
class CoursesController extends Controller
{
public function __construct()
{
//calling auth middleware to check whether user is logged in, if no logged in user they will be redirected to login page
$this->middleware('auth');
}
public function index()
{
if(Gate::denies('manage_courses')){
return redirect(route('home'));
}
$courses = Course::all();
return view('admin.course.index')->with('course', $courses); //pass data down to view
}
public function create()
{
if(Gate::denies('create_courses')){
return redirect(route('home'));
}
$instructors = User::whereHas('role', function ($query) {
$query->where('role_id', 2); })->get()->pluck('name'); //defining instructor variable to call in create.blade.php. Followed by specifying that only users with role_id:2 can be viewed in the select form by looping through the pivot table to check each role_id
return view('admin.course.create', compact('instructors')); //passing instructor to view
}
public function store(Request $request)
{
$course = Course::create($request->all()); //request all the data fields to store in DB
$course->instructors()->sync($request->input('instructors', [])); //input method retrieves all of the input values as an array
if($course->save()){
$request->session()->flash('success', 'The course ' . $course->title . ' has been created successfully.');
}else{
$request->session()->flash('error', 'There was an error creating the course');
}
return redirect()->route ('admin.courses.index');
}
public function destroy(Course $course)
{
if(Gate::denies('delete_courses'))
{
return redirect (route('admin.course.index'));
}
$course->delete();
return redirect()->route('admin.courses.index');
}
public function edit(Course $course)
{
if(Gate::denies('edit_courses'))
{
return redirect (route('admin.courses.index'));
}
$instructors = User::whereHas('role', function ($query) {
$query->where('role_id', 2); })->get()->pluck('name');
//return view('admin.course.edit', compact('instructors'));
return view('admin.course.edit', compact('instructors'))->with([
'course' => $course
]);
}
public function update(Request $request, Course $course)
{
$course->update($request->all());
if ($course->save()){
$request->session()->flash('success', $course->title . ' has been updated successfully.');
}else{
$request->session()->flash('error', 'There was an error updating ' . $course->title);
}
return redirect()->route('admin.courses.index');
}
public function show(Course $course)
{
return view('admin.course.show', compact('course'));
}
}
Referring to latest comment -
you are updating data with key not id
try this
in controller
$instructors = User::whereHas('role', function ($query) {
$query->where('role_id', 2); })->select('id','name')->get();
in blade
you will need instructors->id to update right value
#foreach($instructors as $id => $instructor)
<option value="{{ $instructor->id }}" {{ in_array($id, old('instructors', [])) ? 'selected' : '' }}>{{ $instructor->name }}
</option>
#endforeach

Laravel pagination is not working with date search

I have a couple of search forms in my app in which pagination works great, but when it comes to date search I only get the first page, when I try to go to the second page I get an undefined $ticket variable. When I look at the URL I can see that it doesn't take the date values with him to the next page.
Here is my code:
<tbody class="searchTable">
#foreach($ticket as $tickets)
<tr>
<td>
{{Carbon::parse($tickets->created_at)->format('m/d/Y')}}
</td>
<td>{{$tickets->id}}</td>
<td>{{$tickets->clientName}}</td>
<td>
{{Carbon::parse($tickets->dueDate)->format('m/d/Y')}}
</td>
<td>{{$tickets->refNumber}}</td>
<td>{{$tickets->invoiceNumber}}</td>
<td>{{$tickets->jobLocation}}</td>
<td>{{$tickets->workDescription}}</td>
<td>{{$tickets->jobStatus}}</td>
</tr>
#endforeach
</tbody>
{!! $ticket->appends(Request::only('_token','search'))->render() !!}
This is the controller:
$ticket = DB::table('tickets')
->whereBetween('created_at', [$newDateFrom, $newDateTo])
->orderBy('created_at', 'desc')
->paginate(10);
return view('ticketsView', compact('ticket'));
Here is my solution:
I have the same view for different search requests so I append the results to the paginator so it will have it on the next pages as well. The name is the value of the name attribute in the search form. In my case I had multiple. Here is an example:
{!! $ticket->appends(Request::only(['dateFrom'=>'dateFrom', 'dateTo'=>'dateTo', 'search'=>'search', 'filter'=>'filter', 'dueDateFrom'=>'dueDateFrom','dueDateTo'=>'dueDateTo']))->render() !!}
So now if my search results will contain in the URL dateTo and dateFrom values for example then it will be saved to all pages. It's important to understand that these values come from the name attribute of your search form.
Here is an example:
<form class="form-horizontal" role="form" method="GET" action="/ticket/searchresults" accept-charset="UTF-8" enctype="multipart/form-data">
<div class="text-centered">
<p><strong>Search by dates:</strong></p>
</div>
<div class="form-group">
<label for="filter">Select Client (optional)</label>
<select class="form-control" name="filter" type="text">
<option disabled selected> -- select client -- </option>
#foreach($selectClient as $selectClients)
<option value="{{$selectClients->name}}">{{$selectClients->name}}</option>
#endforeach
</select>
</div>
<div class="form-group">
<label for="dateFrom">From:</label>
<input class="datepicker2 form-control" name="dateFrom" type="text" required/>
</div>
<div class="form-group">
<label for="dateTo">To:</label>
<input class="datepicker2 form-control" name="dateTo" type="text" required/>
</div>
<button type="submit" class="btn btn-primary"><span class="fa fa-fw fa-search"></span></button>
</form>

Categories