亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

Table of Contents
1. Loading and parsing JSON data
2. Display data in the Blade template (Basic drop-down menu)
3. Implement cascading drop-down menus (JavaScript interaction)
3.1 Prepare front-end data
3.2 Writing JavaScript Logic
3.3 Considerations of large data sets
Summarize
Home Backend Development PHP Tutorial Efficiently use JSON data to implement cascading drop-down menus in Laravel Blade templates

Efficiently use JSON data to implement cascading drop-down menus in Laravel Blade templates

Jul 23, 2025 pm 07:18 PM
laravel ai Multi-level linkage red

Efficiently use JSON data to implement cascading drop-down menus in Laravel Blade templates

This article details how to load a local JSON file in a Laravel application and pass its data to a Blade template. By processing JSON parsing by the controller, the view layer uses Blade's @foreach instruction to traverse the data, thereby achieving dynamic generation of drop-down menus. In particular, the article also explores in-depth how to combine JavaScript to implement multi-level linkage drop-down menu functions to provide users with dynamic content display based on selection, and provides practical code examples and precautions for implementing such interactions.

In modern web application development, it is often necessary to load data from non-database sources such as local JSON files and present it to users, especially when building dynamic forms or data selectors. The Laravel framework provides a concise mechanism to handle such needs. This article will guide you on how to integrate JSON data into Laravel Blade views and further implement multi-stage linkage drop-down menus.

1. Loading and parsing JSON data

First, you need to read and parse the JSON file in the Laravel controller. This is usually done in a way that handles view rendering.

 <?php namespace App\Http\Controllers;

use Illuminate\Http\Request;

class UserController extends Controller
{
    /**
     * Displays a view to create a user form.
     *
     * @return \Illuminate\View\View
     */
    public function create()
    {
        // Build the full path of the JSON file// The base_path() function returns the absolute path of the project root directory $jsonFilePath = base_path(&#39;resources/data/address.json&#39;);

        // Check if the file exists to avoid errors if (!file_exists($jsonFilePath)) {
            // Handle errors that do not exist in the file according to the actual situation, such as throwing an exception or returning an error message return back()->withErrors('JSON data file does not exist!');
        }

        // Read the content of the JSON file $jsonString = file_get_contents($jsonFilePath);

        // Decode the JSON string into a PHP array// The second parameter true means decode the JSON object into an associative array, rather than the object $details = json_decode($jsonString, true);

        // Check whether the decoding is successful if (json_last_error() !== JSON_ERROR_NONE) {
            // Handle JSON parsing errors return back()->withErrors('JSON data parsing failed:' . json_last_error_msg());
        }

        // Pass the parsed data to the view return view('users.create')->with('details', $details);
    }
}

illustrate:

  • base_path('resources/data/address.json'): The absolute path used to get the JSON file. It is recommended to place such static data files in the resources directory for easy management.
  • file_get_contents(): Read the entire file to a string.
  • json_decode($jsonString, true): Decode the JSON string into a PHP variable. Passing a true parameter converts the JSON object into an associative array, which is more convenient when accessing data through key names in the Blade template.
  • Error handling: Added file existence checking and JSON decoding error checking, which are necessary parts of robust code in production environments.

2. Display data in the Blade template (Basic drop-down menu)

In the Blade view, you can use the @foreach loop to iterate over the array passed by the controller and generate the HTML

Suppose your address.json file structure is as follows:

 [
 {
   "Region": "Naypyitaw Union Territory",
   "Town ": "Za Bu Thi Ri Township",
   "Quarter": "Zay Ya Theik Di Quarter",
   "Postal Code": 1501001
},
 {
   "Region": "Naypyitaw Union Territory",
   "Town ": "Za Bu Thi Ri Township",
   "Quarter": "Pyin Nyar Theik Di Quarter",
   "Postal Code": 1501002
}
]

In the users/create.blade.php file, you can display the Region drop-down menu like this:

 <label for="region">Region:</label>
<select name="region" id="region" class="form-control">
    <option value="">Please select the area</option>
    {{-- Use array_unique to ensure that the area does not repeat --}}
    @foreach($details->unique('Region') as $detail)
       <option value="{{ $detail['Region'] }}">{{ $detail['Region'] }}</option>
    @endforeach
</select>

illustrate:

  • $details is the entire JSON data array passed from the controller.
  • $details->unique('Region'): To avoid duplicate region options in the drop-down menu, we can use the unique() method of the Laravel collection in Blade. This requires that the $details variable is a Laravel collection (can be converted in the controller via collect($details) or directly in Blade using collect($details)->unique('Region')). If $details is just a normal PHP array, you need to handle deduplication in the controller or manually deduplication in Blade.
  • $detail['Region']: Since json_decode uses true parameter, $detail is an associative array, its key is accessed through square brackets[].

3. Implement cascading drop-down menus (JavaScript interaction)

To implement the cascading function of "If the user selects a certain area, only the townships under that area are displayed", we need to combine JavaScript. A common approach is to pass all the data to the front end at once and then filter and fill on the client via JavaScript.

3.1 Prepare front-end data

In order for JavaScript to access $details data, we need to convert it to a format that is available in JavaScript, usually a JSON string, and embedded in the <script> tag.</script>

 <!-- Somewhere in users/create.blade.php -->
<script>
    // Convert the PHP array to a JSON string and assign it to the JavaScript variable const allDetails = @json($details); 
    // Or use JSON.parse(&#39;{!! json_encode($details) !!}&#39;); if stricter escape is required</script>

<label for="region">Region:</label>
<select name="region" id="region" class="form-control">
    <option value="">Please select the area</option>
    @foreach(collect($details)->unique('Region') as $detail)
       <option value="{{ $detail['Region'] }}">{{ $detail['Region'] }}</option>
    @endforeach
</select>

<label for="town" class="mt-3"> Township:</label>
<select name="town" id="town" class="form-control" disabled>
    <option value="">Please select a township</option>
</select>

<label for="quarter" class="mt-3">Block:</label>
<select name="quarter" id="quarter" class="form-control" disabled>
    <option value="">Please select a block</option>
</select>

<label for="postal_code" class="mt-3">Zip Code:</label>
<input type="text" name="postal_code" id="postal_code" class="form-control" readonly>

3.2 Writing JavaScript Logic

Now we will add JavaScript code to listen for changes in area selection and update the township and block drop-down menus dynamically.

 <script>
    // Ensure that document.addEventListener(&#39;DOMContentLoaded&#39;, function () {
        const regionSelect = document.getElementById(&#39;region&#39;);
        const townSelect = document.getElementById(&#39;town&#39;);
        const quarterSelect = document.getElementById(&#39;quarter&#39;);
        const postalCodeInput = document.getElementById(&#39;postal_code&#39;);

        // Clear and disable town and block drop-down menu function resetTownAndQuarter() {
            townSelect.innerHTML = &#39;<option value="">Please select township&#39;;
            townSelect.disabled = true;
            quarterSelect.innerHTML = &#39;<option value="">Please select a block&#39;;
            quarterSelect.disabled = true;
            postalCodeInput.value = &#39;&#39;; // Clear the postal code}

        resetTownAndQuarter(); // Execute regionSelect.addEventListener(&#39;change&#39;, function () {
            const selectedRegion = this.value;
            resetTownAndQuarter(); // reset if (selectedRegion) {
                // Filter out township data matching the selected area const filteredTowns = allDetails.filter(item => item[&#39;Region&#39;] === selectedRegion);

                // Get the list of towns that are not duplicated const uniqueTowns = [...new Set(filteredTowns.map(item => item[&#39;Town &#39;]))]; // Note that &#39;Town &#39; has spaces // Fill in the township drop-down menu uniqueTowns.forEach(town => {
                    const option = document.createElement(&#39;option&#39;);
                    option.value = town;
                    option.textContent = town;
                    townSelect.appendChild(option);
                });
                townSelect.disabled = false; // Enable township drop-down menu}
        });

        townSelect.addEventListener(&#39;change&#39;, function () {
            const selectedRegion = regionSelect.value;
            const selectedTown = this.value;
            quarterSelect.innerHTML = &#39;<option value="">Please select block&#39;; // Reset block quarterSelect.disabled = true;
            postalCodeInput.value = &#39;&#39;; // Clear the postal code if (selectedRegion && selectedTown) {
                // Filter out block data matching the selected area and township const filteredQuarters = allDetails.filter(item => 
                    item[&#39;Region&#39;] === selectedRegion && item[&#39;Town &#39;] === selectedTown
                );

                // Get the list of non-duplicate blocks const uniqueQuarters = [...new Set(filteredQuarters.map(item => item[&#39;Quarter &#39;]))]; // Note that &#39;Quarter &#39; has spaces // Fill the block drop-down menu uniqueQuarters.forEach(quarter => {
                    const option = document.createElement(&#39;option&#39;);
                    option.value = quarter;
                    option.textContent = quarter;
                    quarterSelect.appendChild(option);
                });
                quarterSelect.disabled = false; // Enable the block drop-down menu}
        });

        quarterSelect.addEventListener(&#39;change&#39;, function () {
            const selectedRegion = regionSelect.value;
            const selectedTown = townSelect.value;
            const selectedQuarter = this.value;
            postalCodeInput.value = &#39;&#39;; // Clear the postal code if (selectedRegion && selectedTown && selectedQuarter) {
                // Find the corresponding postal code const matchedDetail = allDetails.find(item => 
                    item[&#39;Region&#39;] === selectedRegion && 
                    item[&#39;Town &#39;] === selectedTown && 
                    item[&#39;Quarter &#39;] === selectedQuarter
                );

                if (matchedDetail) {
                    postalCodeInput.value = matchedDetail[&#39;Postal Code&#39;];
                }
            }
        });
    });
</script>

illustrate:

  • @json($details): This is a convenient directive for Laravel Blade that automatically converts PHP variables to JSON strings safely and encodes HTML entities, which can be used directly in JavaScript.
  • document.addEventListener('DOMContentLoaded', ...): Ensure that JavaScript code is executed after the HTML document is fully loaded and parsed.
  • filter() and map(): Common methods for JavaScript arrays, used to filter and transform data.
  • [...new Set(...)]: A concise JavaScript syntax for extracting unique elements from an array.
  • disabled property: Disable subsequent drop-down menus before the user makes a valid choice.
  • Note the key name: There are spaces at the end of the Town and Quarter key names in your JSON data. Be sure to keep these spaces when accessing in JavaScript, for example item['Town ']. In actual development, it is recommended to keep the key names standardized and avoid spaces.

3.3 Considerations of large data sets

If your JSON file is very large, loading all data to the front end at once can cause performance issues. In this case, a better approach is:

  1. Initial loading: Only load data from the first drop-down menu (such as "area") when the page is loading.
  2. AJAX request: When a user selects a region, an AJAX request is sent to the backend via JavaScript (for example, using the fetch API or Axios), taking the selected region as a parameter.
  3. Backend filtering: After the backend controller receives the request, it filters out the corresponding township data from the JSON file according to the parameters and returns it in JSON format.
  4. Front-end update: After JavaScript receives the data returned by the back-end, dynamically fills the township drop-down menu.
  5. Repeat: Repeat this process for subsequent blocks, etc. drop-down menus.

This method can reduce the amount of data loaded on the initial page and improve the user experience.

Summarize

Through the above steps, you have learned how to load and parse local JSON files in your Laravel application and display their data dynamically in your Blade template. Whether it is a simple drop-down menu or a complex cascading selector, combined with Laravel's back-end processing power and front-end JavaScript interactivity, you can build powerful and user-friendly forms. In actual projects, be sure to consider the data size and choose the most suitable loading and interaction strategy.

The above is the detailed content of Efficiently use JSON data to implement cascading drop-down menus in Laravel Blade templates. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to choose a free market website in the currency circle? The most comprehensive review in 2025 How to choose a free market website in the currency circle? The most comprehensive review in 2025 Jul 29, 2025 pm 06:36 PM

The most suitable tools for querying stablecoin markets in 2025 are: 1. Binance, with authoritative data and rich trading pairs, and integrated TradingView charts suitable for technical analysis; 2. Ouyi, with clear interface and strong functional integration, and supports one-stop operation of Web3 accounts and DeFi; 3. CoinMarketCap, with many currencies, and the stablecoin sector can view market value rankings and deans; 4. CoinGecko, with comprehensive data dimensions, provides trust scores and community activity indicators, and has a neutral position; 5. Huobi (HTX), with stable market conditions and friendly operations, suitable for mainstream asset inquiries; 6. Gate.io, with the fastest collection of new coins and niche currencies, and is the first choice for projects to explore potential; 7. Tra

Ethena treasury strategy: the rise of the third empire of stablecoin Ethena treasury strategy: the rise of the third empire of stablecoin Jul 30, 2025 pm 08:12 PM

The real use of battle royale in the dual currency system has not yet happened. Conclusion In August 2023, the MakerDAO ecological lending protocol Spark gave an annualized return of $DAI8%. Then Sun Chi entered in batches, investing a total of 230,000 $stETH, accounting for more than 15% of Spark's deposits, forcing MakerDAO to make an emergency proposal to lower the interest rate to 5%. MakerDAO's original intention was to "subsidize" the usage rate of $DAI, almost becoming Justin Sun's Solo Yield. July 2025, Ethe

What is Binance Treehouse (TREE Coin)? Overview of the upcoming Treehouse project, analysis of token economy and future development What is Binance Treehouse (TREE Coin)? Overview of the upcoming Treehouse project, analysis of token economy and future development Jul 30, 2025 pm 10:03 PM

What is Treehouse(TREE)? How does Treehouse (TREE) work? Treehouse Products tETHDOR - Decentralized Quotation Rate GoNuts Points System Treehouse Highlights TREE Tokens and Token Economics Overview of the Third Quarter of 2025 Roadmap Development Team, Investors and Partners Treehouse Founding Team Investment Fund Partner Summary As DeFi continues to expand, the demand for fixed income products is growing, and its role is similar to the role of bonds in traditional financial markets. However, building on blockchain

Using Form Requests for Validation in Laravel. Using Form Requests for Validation in Laravel. Jul 30, 2025 am 05:04 AM

Use FormRequests to extract complex form verification logic from the controller, improving code maintainability and reusability. 1. Creation method: Generate the request class through the Artisan command make:request; 2. Definition rules: Set field verification logic in the rules() method; 3. Controller use: directly receive requests with this class as a parameter, and Laravel automatically verify; 4. Authorization judgment: Control user permissions through the authorize() method; 5. Dynamic adjustment rules: dynamically return different verification rules according to the request content.

How can we avoid being a buyer when trading coins? Beware of risks coming How can we avoid being a buyer when trading coins? Beware of risks coming Jul 30, 2025 pm 08:06 PM

To avoid taking over at high prices of currency speculation, it is necessary to establish a three-in-one defense system of market awareness, risk identification and defense strategy: 1. Identify signals such as social media surge at the end of the bull market, plunge after the surge in the new currency, and giant whale reduction. In the early stage of the bear market, use the position pyramid rules and dynamic stop loss; 2. Build a triple filter for information grading (strategy/tactics/noise), technical verification (moving moving averages and RSI, deep data), emotional isolation (three consecutive losses and stops, and pulling the network cable); 3. Create three-layer defense of rules (big whale tracking, policy-sensitive positions), tool layer (on-chain data monitoring, hedging tools), and system layer (barbell strategy, USDT reserves); 4. Beware of celebrity effects (such as LIBRA coins), policy changes, liquidity crisis and other scenarios, and pass contract verification and position verification and

What is Zircuit (ZRC currency)? How to operate? ZRC project overview, token economy and prospect analysis What is Zircuit (ZRC currency)? How to operate? ZRC project overview, token economy and prospect analysis Jul 30, 2025 pm 09:15 PM

Directory What is Zircuit How to operate Zircuit Main features of Zircuit Hybrid architecture AI security EVM compatibility security Native bridge Zircuit points Zircuit staking What is Zircuit Token (ZRC) Zircuit (ZRC) Coin Price Prediction How to buy ZRC Coin? Conclusion In recent years, the niche market of the Layer2 blockchain platform that provides services to the Ethereum (ETH) Layer1 network has flourished, mainly due to network congestion, high handling fees and poor scalability. Many of these platforms use up-volume technology, multiple transaction batches processed off-chain

Is the currency circle illegal? Is the currency circle illegal? Jul 29, 2025 pm 05:39 PM

Whether the currency circle violates the law depends on the laws and nature of the country where it is located. Digital currencies themselves are considered legal assets in some countries, but their transactions are subject to pre-backwashing and identity verification regulations; while in others, they may be completely banned. Common legal risks include pre-laundering, illegal fundraising, fraud, terrorist financing, evasion of foreign exchange controls, and operating financial business without permission. To avoid risks, we should understand local regulations, choose compliance platforms, protect asset security, and be wary of high-yield scams.

How to build a REST API with Laravel? How to build a REST API with Laravel? Jul 30, 2025 am 03:41 AM

Create a new Laravel project and start the service; 2. Generate the model, migration and controller and run the migration; 3. Define the RESTful route in routes/api.php; 4. Implement the addition, deletion, modification and query method in PostController and return the JSON response; 5. Use Postman or curl to test the API function; 6. Optionally add API authentication through Sanctum; finally obtain a clear structure, complete and extensible LaravelRESTAPI, suitable for practical applications.

See all articles