Searching for data between two specific dates can be achieved in Laravel Vue by utilizing the filter

I've successfully implemented a search feature for normal fields in my form. However, I'm encountering difficulty when trying to search within a date range. Here's my controller code:

public function index() {

$query = Matter::query();

$query->when(request('search_client','search_file_ref','search_file_status','search_date_from','search_date_to'), function($query){
$query->where('client_company', 'like', '%' . request('search_client') . '%');
$query->where('file_ref', 'like', '%' . request('search_file_ref') . '%');
$query->where('status', 'like', '%' . request('search_file_status') . '%');

$query->whereBetween('created_at', ['search_date_from', 'search_date_to']);
});
return $query->orderBy('id','asc')->get();

}

In the view section of my application, I have the following setup for searching within a date range:

                <b-col md="4">
                    <form @submit.prevent="searchDateFrom">
                        <label for="">Choose File Status:</label>
                <div class="input-group">

                    <input
                        v-model="search_date_from"
                        type="date"
                        placeholder="Search File Status"
                        class="form-control"
                    />
                    <input
                        v-model="search_date_to"
                        type="date"
                        placeholder="Search File Status"
                        class="form-control"
                    />
                    <div class="input-group-append">
                        <button type="submit" class="btn btn-primary">
                            <i class="fas fa-search"></i>
                        </button>
                    </div>
                </div>
            </form>
            </b-col>

...

data(){
    return {
        search_client: "",
        search_file_ref: "",
        search_file_status: "",
        search_date_from: "",
        search_date_to: "",
        matters:[]
    }
},

...

searchDateFrom(){
        axios.get('/api/auth/matter?search_date_from=' + this.search_date_from + 'search_date_to=' + this.search_date_to)
        .then(response => this.matters = response.data)

    },

By directly specifying the date range in the controller like this, it works:

$query->whereBetween('created_at', ['2022-06-01', '2022-06-07']);

But when including the request variables like this:

$query->whereBetween('created_at', ['search_date_from', 'search_date_to']);

The API does not return any data. It seems that there might be an issue with how I'm handling the request. The model structure is as follows:

{
use HasFactory;
protected $fillable = [
    'matter_type','client_company','description','file_group',
    'control_account','pic','lawyer','task_assign','task_recipient',
    'file_ref','remark','purchaser_1','purchaser_2','status'
];
protected $casts = [
'created_at' => 'datetime:m / d / Y',
];
}

I can successfully retrieve and search through data using fields other than dates. My goal is to allow users to input two dates and retrieve results within that specific range.

Answer №1

Your query is accurate, but there is a minor error where you failed to enclose your date parameters in the request helper function. Instead of using dates from the request, you mistakenly passed string literals search_date_from and search_date_to to the whereBetween method.

Original code snippet:

$query->whereBetween('created_at', ['search_date_from', 'search_date_to']);

Corrected version:

$query->whereBetween('created_at', [request('search_date_from'), request('search_date_to')]);

Please refer to the corrected code below.

public function index() {

        $query = Matter::query();

        $query->when(request('search_client','search_file_ref','search_file_status','search_date_from','search_date_to'), function($query){
            $query->where('client_company', 'like', '%' . request('search_client') . '%');
            $query->where('file_ref', 'like', '%' . request('search_file_ref') . '%');
            $query->where('status', 'like', '%' . request('search_file_status') . '%');

            $query->whereBetween('created_at', [request('search_date_from'), request('search_date_to')]);
        });
        return $query->orderBy('id','asc')->get();

    }

Answer №2

Initially, the variables in this section are written as strings.

$query->whereBetween('created_at', ['search_date_from', 'search_date_to']); 

An alternative approach would be to write it as follows:

$query->whereBetween('created_at', [$search_date_from, $search_date_to]); 

Personally, I find it clearer to write it like this:

$query->whereBetween(DB::raw("DATE('created_at')"), array($from, $to));

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issue with Laravel Vue search-dropdown and other components failing to render correctly for certain users

We are currently implementing a searchable dropdown menu for our web application using a vue component. Strangely, the component fails to load on my local version (xampp) as well as on the deployed website. However, it displays properly on another develope ...

What is the significance of having a timer in a Redux reducer to prompt a re-rendering process?

Encountered some unusual behavior that I need to understand better Here is the code for my reducer. Strangely, the component linked to the redux state does not re-render with this code. Despite confirming through developer tools that the state updates cor ...

How can AngularJS apps handle authentication?

Seeking input on user authentication with AngularJS and Zend... I currently have Angular on the client side and Zend on the server side handling authentication successfully. However, I'm looking for best practices and code examples for enhancing the ...

Utilizing Vue's looping functionality to dynamically insert CSS class names

As a newcomer to Vue, I am facing an issue with handling an array of objects. My goal is to dynamically assign a className to the wrapper of a loop based on a condition. For instance: <div v-for="({time, date, name}, i) in myObject" :key=" ...

Getting the raw exception message in Laravel without any HTML formatting can be accomplished by accessing the `

When interacting with the Laravel backend, I frequently make ajax requests. While processing the request data on the backend, there are instances where exceptions are thrown. By default, Laravel generates HTML pages with exception messages. However, my r ...

Did I incorrectly associate the function with the button causing it to always be executed?

I am working on a PHP page, where I have some initial content followed by session initialization code: <?php session_start(); ?> The requirement is to display a disconnect button only if the user is logged in, indicated by the presence of $_SESS ...

How can we integrate a real-time counter into a text field in Laravel Nova?

Currently, I am utilizing the Nova Admin panel in my Laravel project. I have integrated a new resource that requires the admin to input text into various fields. One of these fields is a meta-title or meta description. While everything seems to be working ...

What is the best way to create three buttons for selecting various parameters?

I have a code snippet where I want to assign different parameters to each button when clicked. However, despite my logic, the functionality is not working as expected. Can someone help me with the correct syntax? For example, if I click the "Start (Easy) ...

Accessing object properties in the data of a Vue component

Recently delving into Vue, I've run into a bit of confusion. My app connects to a JSON Api using usePage(). The usePage() function allows me to utilize the "page" object within the <template> tag like so: <p>This product costs {{page.pric ...

The $dbServiceProvider in AngularJS, Sqlite, Electron seems to be unrecognized

I am currently working on an electron app that is supposed to display and retrieve items from a SQL database I created. However, I keep encountering an unknown provider error. Despite trying various solutions found online, the issue persists and I am unab ...

Utilizing CDN script with Shopify: A guide to optimization

I am currently utilizing VueJs in the development of a Shopify theme using Shopify Cli and Store 2.0. To incorporate Vue, I initially attempted to install it through a CDN script within my theme.liquid file. <script src="{{ 'vue.global.js&apos ...

React Hooks: Issue with UseRef not detecting events from Material UI Select component

I'm currently utilizing React Hooks in my project. I am attempting to trigger an onclick event using the useRef hook. const component1: React.FC<Props> = props { const node =useRef<HTMLDivElement>(null); const ClickListe ...

Submit function causes mutation in React form state

My current project involves learning React on my own and creating a small single-page React app using an Axios API. I'm facing a persistent issue with a POST request that keeps failing. After extensively using console.log, it appears that the form inp ...

Is it possible for the client to prevent the blocking of the Cross-Origin Resource Sharing (CORS) error?

I am encountering an issue with my web app that involves CORS operations when making $.getJSON AJAX calls. Typically, this functions properly on most client browsers due to the server having CORS enabled. However, I recently discovered that when using IE 1 ...

Develop a responsive image component with flexible dimensions in React

I am currently working on developing a dynamic image component that utilizes the material-ui CardMedia and is configured to accept specific height and width parameters. The code snippet I have is as follows: interface ImageDim extends StyledProps { wid ...

Having trouble adding a new key to an empty data object in Vue.js?

I have a question regarding Vue data manipulation. In my code, I have initialized the data with an empty object like this: data(){ return { myObj: {} } } and defined a method as follows: methods: { changeMyObj() { this.myObj.newKey = 'aa ...

At random intervals, a ReferenceError is triggered stating that Vue is not defined

While working on an application that uses templates rendered by Apache Velocity, I encountered the error "Uncaught ReferenceError: Vue is not defined" when trying to incorporate vue.js components. Oddly enough, this error is not consistent - it occurs most ...

Retrieve the data attribute associated with the chosen dropdown selections

I'm currently facing an issue with assigning a custom data attribute to a select box option and then transferring that value to a hidden form field. Here is the HTML I am working with: <select id="sampleorder" multiple="multiple"> <option ...

How to correctly insert foreign keys in Hibernate using @OneToMany mapping

I am having some difficulty understanding Hibernate. In my simple Spring application with Spring Security, I use a Principal to verify if the user exists in the database before logging in. Therefore, I cannot perform something like User globaluser = user; ...

Utilizing the Google Translate API within an ASP MVC framework to translate a div's content from English to Arabic

Currently, I am working on a small project that involves two divs: one for English and another for Arabic. Despite creating the project, I am encountering an issue with getting the translation from English to Arabic. Below is the code I have attempted, but ...