I have a method to return results from db from startDate to endDate passing in like parameters in postman.
Everything seems to be working fine but it returns all results from database.
I think that problem could be with parameters..
public function getInvoices($fromDate = null, $toDate = null)
{
$query = $this->entityManager->getRepository(Invoice::class)
->createQueryBuilder('ur')
->select('ur')
->orderBy('ur.invoiceDate', 'ASC');
if($fromDate) {
$query
->andWhere('t.invoiceDate >= :startDate')
->setParameter('startDate', new \DateTime($fromDate));
}
if($toDate) {
$query
->andWhere('t.invoiceDate <= :endDate')
->setParameter('endDate', new \DateTime($toDate));
}
return $query->getQuery()->getResult();
}
And I am calling this method in my controller like:
$data = [];
$responseData = $this->invoiceService->getInvoices(
#$this->data['startDate'],
#$this->data['endDate']
);
I pass this two parameters via postman and it returns all results:
Here is an image: here
Related
I have a filter like this
I have a working date filter with laravel. The problem is that if I don't filter my records when no records are shown.
public function index(Request $request)
{
$stats = [
'done' => UserTransaction::where('status', UserTransaction::STATUS['done'])->count(),
'canceled' => UserTransaction::where('status', UserTransaction::STATUS['canceled'])->count(),
'all' => UserTransaction::count(),
];
if ($request->start_date && $request->end_date){
$dateS = new Carbon($request->start_date);
$dateE = new Carbon($request->end_date);
$result = UserTransaction::whereBetween('created_at', [$dateS->format('Y-m-d'), $dateE->format('Y-m-d')])->get();
}
if ($request->search) {
$transactions = UserTransaction::search($request->search)->paginate(5);
} else {
$transactions = UserTransaction::paginate(5);
}
if ($transactions->count() == 0 && $request->search ) {
msg()->warning('No records found');
}
return view('transaction::admin.index', compact('transactions', 'stats', 'result'));
}
I would consider changing your logic a little to allow for people to specify either just a start date or just an end date which could be entirely possible from a usability perspective.
Create a query builder, then add where clauses for the start_date and end_date if they appear in your $request object. If they do not appear then you can use the query as you have been doing so already.
$transactions = Transaction::query();
if ($request->start_date) {
$query->whereDate('start_date', '>=', new Carbon($request->start_date));
}
if ($request->end_date) {
$query->whereDate('end_date', '<=', new Carbon($request->end_date));
}
if ($requer->search) {
$query->search($request->search);
}
$query->paginate(5);
You can use if condition inside query and remove outer if condition
$result = UserTransaction::where(function($query)use($request){
if(!empty($request->start_date)&&!empty($request->end_date)){
$dateS = new Carbon($request->start_date);
$dateE = new Carbon($request->end_date);
$query->whereBetween('created_at', [$dateS->format('Y-m-d'), $dateE->format('Y-m-d')]);
}
})->get();
I'm working on a Symfony project that makes use of a
Repository file in which I have declared and created an instance of a query builder
(repository1)
$mk = $this->createQueryBuilder('up');
$later = date("Y-m-d", strtotime("-3 months"));
$today = date("Y-m-d");
$mk->andWhere('up.period BETWEEN :start AND :end');
$mk->setParameter('start', $later);
$mk->setParameter('end', $today);
return $mk->getQuery()->getResult();
automatically this generates data for my page between the above dates.
Now I want to create a form where I can make a search between two dates.
with the intention of passing the posted data from this form to my controller into my method below
My controller below (controller1)
protected function getData(EntityManagerInterface $entityManager,Request $request) {
// this code to get data from repository
$entityManager->getRepository(repository1::class)->getName()
// receive posted data
$date1 = $request->get('date');
$date2 = $request->get('date');
// now how to pass data to my repository1
}
Please how do I edit what I have to post data from within my controller to my (repository1)
so then it would be
$mk = $this->createQueryBuilder('up');
$later = $date1;
$today = $date2;
$mk->andWhere('up.period BETWEEN :start AND :end');
$mk->setParameter('start', $later);
$mk->setParameter('end', $today);
return $mk->getQuery()->getResult();
is this even possible, or im over thinking it?
RepositoryClass
public function getByStartEndDate(DateTimeInterface $start, DateTimeInterface $end)
{
return $this->createQueryBuilder('up')
->andWhere('up.period BETWEEN :start AND :end')
->setParameter('start', $start)
->setParameter('end', $end)
->getQuery()
->getResult()
;
}
Controller Class
private function getData(Request $request, RepositoryClass $repo)
{
// May need to convert these to DateTime objects
$start = $request->get('start');
$end = $request->get('end');
$records = $repo->getByStartEndDate($start, $end);
// do what you want with the records here
}
You can give the dates as parameters to your method.
Controller Class:
protected function getData(EntityManagerInterface $entityManager,Request $request) {
$start = $request->get('start') ? new \DateTime($request->get('start')) : null;
$end = $request->get('end') ? new \DateTime($request->get('end')) : null;
$result = $entityManager->getRepository(Entity::class)->getName($start, $end);
// do with result as desired
}
Repository Class:
public function getName(\DateTimeInterface $start, \DateTimeInterface $end)
{
return $this->createQueryBuilder('up')
->andWhere('up.period BETWEEN :start AND :end')
->setParameter('start', $start)
->setParameter('end', $end)
->getQuery()
->getResult()
;
}
I am having a hard time with Laravel. I have a query that returns all the table columns. The problem is that a field "foto" returns as an empty string in the JSON when I use the "get" or "find" methods. Paginate it works as expected.
This query:
$resultado = $query
->where('id_admin', '=', $id_admin)
->with('telasPermissao.itemPermissao')
->paginate(50);
foto comes as:
"foto": "data/image:93483940349"
Now, with this:
$resultado = $query
->where('id_admin', '=', $id_admin)
->with('telasPermissao.itemPermissao')
->find(1);
$resultado = $query
->where('id_admin', '=', $id_admin)
->with('telasPermissao.itemPermissao')
->get(50);
foto comes as:
"foto" : ""
I am returning the data from the controller like this:
return response()->json($resultado, 200);
In my operador model I have the following mutator:
public function getFotoAttribute($value)
{
if ($value != null)
{
return pg_escape_string(fgets($value));
}
return null;
}
Try updating your mutator like this:
public function getFotoAttribute()
{
if ($this->attributes['foto'] != null)
{
return pg_escape_string(fgets($this->attributes['foto']));
}
return null;
}
After fighting 2 hours, I give up. As a workoaround I used this to replace the find method.
$resultado = $query->where('id_admin', '=', $id_admin)->with('telasPermissao.itemPermissao')->where('id', 517 )->paginate(1)
If someone knows what happened please post an answer.
This is the function I am using in my model
public function user_birthday() {
$this->db->select('birth_day')
->from('informations')
->where(DATE_FORMAT(FROM_UNIXTIME('birth_day'), '%m-%d') = DATE_FORMAT(NOW(), '%m-%d'));
$q = $this->db->get();
return $q->result();
}
function in controller like $this->data['user'] = $this->users_m->user_birthday(); that way
and code in the view is
if (!empty($user)):
echo $user;
else:
echo "No dob found";
endif;
This is one of those circumstances where Query Builder is more trouble that it is worth. Try this
$q= $this->db->query("SELECT birth_day FROM informations WHERE DATE_FORMAT(birth_day, '%m-%d') = DATE_FORMAT(NOW(), '%m-%d')");
//return empty array if not records found
return $q->num_rows() > 0 ? $q->result() : [];
If you really, really, really want to use Query Builder then this
$q = $this->db
->select('birth_day')
->where("DATE_FORMAT(birth_day, '%m-%d')=", "DATE_FORMAT(NOW(), '%m-%d')", FALSE)
->get('informations');
return $q->num_rows() > 0 ? $q->result() : [];
In the code below,I'm getting an empty array for the third if-else statement. What I'm trying is that get a range of date from user and showing the data from the table accordingly. My first if-else statement is returning desired results but the second one is returning empty array.
Controller:
public function bookings()
{
if($this->userlib->isLoggedIn())
{
if($this->userlib->isAdmin())
{
$this->load->view('admin_search_booking');
$date_posted_from = $this->input->post('date_posted_from');
$date_posted_till = $this->input->post('date_posted_till');
$date_posted_on = $this->input->post('date_posted_on');
if(is_null($date_posted_from) && is_null($date_posted_till) && is_null($date_posted_on))
{
$total_trails = $this->admin_panel_model->total_trail();
var_dump($total_trails);
}
elseif(!is_null($date_posted_on))
{
$total_trails = $this->admin_panel_model->filter_on_date($date_posted_on);
var_dump($total_trails);
}
elseif(!is_null($date_posted_from) && !is_null($date_posted_till))
{
$total_trails = $this->admin_panel_model->filter_by_date($date_posted_from, $date_posted_till);
var_dump($total_trails);
}
}
}
else
{
echo "User not Logged In";
}
}
Model filter_by_date :-
public function filter_by_date($date_posted_from, $date_posted_till)
{
$query = $this->db->select('*')
->where('date >=', $date_posted_from)
->where('date <=', $date_posted_till)
->get($this->search);
return $query->result();
}
isLoggedIn :-
public function isLoggedIn()
{
if($this->ci->session->email)
return true;
else
return false;
}
Change your model function like this
public function filter_by_date($date_posted_from="", $date_posted_till="")
{
$query = $this->db->select('*');
if($date_posted_from)
$this->db->where('date >=', $date_posted_from);
if($date_posted_till)
$this->db->where('date <=', $date_posted_till);
$this->db->get($this->search);
return $query->result();
}
//This may help you put your table name in your select statement and update where clause
public function filter_by_date($date_posted_from, $date_posted_till){
$date_posted_from='2015-10-10';
$date_posted_till='2015-10-16';
$query = $this->db->select('*')->from('Your_Table_Name')
->where("date >= '".$date_posted_from."'")
->where("date <= '".$date_posted_till."'")
->get($this->search);
return $query->result();
}
Use $this->db->last_query(); after filter_by_date() and check what query is actually being executed. And also make sure there are records exists in the date range you are searching for.
Or simply use straight forward query,
$Q = $this->db->query("select * from table_name where date >='".$date_posted_from."' and date <='".$date_posted_to."'");
return $Q->result_array();