Close Menu
    DevStackTipsDevStackTips
    • Home
    • News & Updates
      1. Tech & Work
      2. View All

      Sunshine And March Vibes (2025 Wallpapers Edition)

      May 14, 2025

      The Case For Minimal WordPress Setups: A Contrarian View On Theme Frameworks

      May 14, 2025

      How To Fix Largest Contentful Paint Issues With Subpart Analysis

      May 14, 2025

      How To Prevent WordPress SQL Injection Attacks

      May 14, 2025

      I test a lot of AI coding tools, and this stunning new OpenAI release just saved me days of work

      May 14, 2025

      How to use your Android phone as a webcam when your laptop’s default won’t cut it

      May 14, 2025

      The 5 most customizable Linux desktop environments – when you want it your way

      May 14, 2025

      Gen AI use at work saps our motivation even as it boosts productivity, new research shows

      May 14, 2025
    • Development
      1. Algorithms & Data Structures
      2. Artificial Intelligence
      3. Back-End Development
      4. Databases
      5. Front-End Development
      6. Libraries & Frameworks
      7. Machine Learning
      8. Security
      9. Software Engineering
      10. Tools & IDEs
      11. Web Design
      12. Web Development
      13. Web Security
      14. Programming Languages
        • PHP
        • JavaScript
      Featured

      Strategic Cloud Partner: Key to Business Success, Not Just Tech

      May 14, 2025
      Recent

      Strategic Cloud Partner: Key to Business Success, Not Just Tech

      May 14, 2025

      Perficient’s “What If? So What?” Podcast Wins Gold at the 2025 Hermes Creative Awards

      May 14, 2025

      PIM for Azure Resources

      May 14, 2025
    • Operating Systems
      1. Windows
      2. Linux
      3. macOS
      Featured

      Windows 11 24H2’s Settings now bundles FAQs section to tell you more about your system

      May 14, 2025
      Recent

      Windows 11 24H2’s Settings now bundles FAQs section to tell you more about your system

      May 14, 2025

      You can now share an app/browser window with Copilot Vision to help you with different tasks

      May 14, 2025

      Microsoft will gradually retire SharePoint Alerts over the next two years

      May 14, 2025
    • Learning Resources
      • Books
      • Cheatsheets
      • Tutorials & Guides
    Home»Development»Streamlining Route Parameters in Laravel Using URL Defaults

    Streamlining Route Parameters in Laravel Using URL Defaults

    December 7, 2024

    Streamlining Route Parameters in Laravel Using URL Defaults

    Managing URL parameters in Laravel applications, particularly those with multiple languages or complex routing patterns, can become repetitive. Laravel provides an elegant solution through URL defaults, allowing you to set application-wide default values for URL parameters. Let’s explore this powerful feature’s implementation.

    Understanding URL Defaults

    URL defaults enable you to define global default values for URL parameters across your application. This proves particularly valuable for handling common parameters like language preferences or regional settings.

    Let’s implement URL defaults in a multilingual application with currency support:

    <?php
    
    namespace AppHttpMiddleware;
    
    use Closure;
    use IlluminateHttpRequest;
    use IlluminateSupportFacadesURL;
    
    class SetUrlDefaults
    {
        public function handle(Request $request, Closure $next)
        {
            URL::defaults([
                'locale' => $request->user()?->preferred_language ?? config('app.locale'),
                'currency' => $request->user()?->preferred_currency ?? 'USD'
            ]);
            return $next($request);
        }
    }
    

    Register the middleware in your kernel:

    <?php
    
    namespace AppHttp;
    
    class Kernel extends HttpKernel
    {
        protected $middleware = [
            // ... other middleware
            AppHttpMiddlewareSetUrlDefaults::class,
        ];
    }
    

    Implementing the routing structure:

    <?php
    
    use AppHttpControllersProductController;
    
    Route::prefix('{locale}/{currency}')->group(function () {
        Route::get('products', [ProductController::class, 'index'])
            ->name('products.index');
            
        Route::get('products/{product}', [ProductController::class, 'show'])
            ->name('products.show');
    });
    
    class ProductController extends Controller
    {
        public function index()
        {
            // URLs will automatically use default locale and currency
            return view('products.index', [
                'products' => Product::paginate(20),
                'categoryUrl' => route('products.category', ['category' => 'electronics'])
            ]);
        }
    
        public function changePreferences(Request $request, $locale, $currency)
        {
            $request->user()->update([
                'preferred_language' => $locale,
                'preferred_currency' => $currency
            ]);
    
            return redirect()->back();
        }
    }
    

    In your views, you can generate URLs without explicitly specifying the defaults:

    <!-- Products listing view -->
    <nav>
        <a href="{{ route('products.index') }}">{{ __('All Products') }}</a>
        <a href="{{ route('products.show', $product) }}">{{ $product->name }}</a>
    </nav>
    
    <!-- Only override when needed -->
    <a href="{{ route('products.index', ['currency' => 'EUR']) }}">
        {{ __('View in Euros') }}
    </a>
    

    This implementation provides clean, maintainable routing while automatically handling user preferences across your application.


    The post Streamlining Route Parameters in Laravel Using URL Defaults appeared first on Laravel News.

    Join the Laravel Newsletter to get all the latest
    Laravel articles like this directly in your inbox.

    Source: Read More 

    Hostinger
    Facebook Twitter Reddit Email Copy Link
    Previous ArticlePackagist.org is ending support for Composer 1.x
    Next Article Dynamic Form Validation in Laravel with prohibited_if

    Related Posts

    Machine Learning

    Georgia Tech and Stanford Researchers Introduce MLE-Dojo: A Gym-Style Framework Designed for Training, Evaluating, and Benchmarking Autonomous Machine Learning Engineering (MLE) Agents

    May 15, 2025
    Machine Learning

    A Step-by-Step Guide to Build an Automated Knowledge Graph Pipeline Using LangGraph and NetworkX

    May 15, 2025
    Leave A Reply Cancel Reply

    Continue Reading

    Microsoft Presents a Comprehensive Framework for Securing Generative AI Systems Using Lessons from Red Teaming 100 Generative AI Products

    Machine Learning

    CES 2025: The 7 most advanced smart glasses we tried on – and loved

    News & Updates

    Rollout of Apple’s “Apple Intelligence” suite is delayed by the EU

    Artificial Intelligence

    I underestimated these Shokz’ open-ear headphones – they’re now an everyday favorite

    News & Updates
    Hostinger

    Highlights

    Understanding the Key Layers of UI Interaction

    May 17, 2024

    It’s no surprise, dear reader, that most web interactions are lacking, and few interfaces have…

    CVE-2025-47270 – Nimiq Albatross Denial of Service Buffer Overflow

    May 12, 2025

    CVE-2025-4070 – PHPGurukul Rail Pass Management System SQL Injection Vulnerability

    April 29, 2025

    New Frontiers, Old Tactics: Chinese Espionage Group Targets Africa & Caribbean Govts

    May 23, 2024
    © DevStackTips 2025. All rights reserved.
    • Contact
    • Privacy Policy

    Type above and press Enter to search. Press Esc to cancel.