Posts

Since 2024
Laravel 11 streamlined configuration files
Laravel 11 streamlined configuration files

One of my favorite features in Laravel 11 is the streamlined configuration files. During the development of Laravel 11 all configuration files were removed from the default Laravel installation. However, a few weeks before release, Taylor decided to re-include a slimmed version of the config files in a default Laravel install but left the option to remove any files or options you don't need. Let's dig a little deeper to understand how this works to avoid mistakes and get the slimmest application possible. After all, the config files can add a lot of noise to your application. You also need to be careful to keep them up-to-date, as they are constantly changing. This combination is why I'm glad to see this feature in Laravel 11. Internally, Laravel merges your configuration file with a framework default. So, if your app has a config/database.php file, it will be merged with Laravel's internal config/database.php file. What's interesting here is the merge. On the surface, this merges top-level options (a shallow merge). This means you can further slim your configuration files by removing any top-level options you do not use. Again, any options in your configuration file will automatically merge with the Laravel defaults. Let's look at a quick example using the following config/app.php file within a Laravel 11 application: <?php return [ 'timezone' => 'America/Kentucky/Louisville', 'custom_option' => 'foo' ]; The resulting configuration would be all of the core app configuration options (app.name, app.env, app.debug, etc) with app.timezone overwritten and your app.custom_option added. This merge works well for files with top-level options. However, some of the configuration files have nested "driver" options. Laravel does a bit more when performing this merge. Although it is not recursive, Laravel will merge some common nested options. For example, database.connections, filesystem.disks, and more. With this additional merge, instead of needing to include all the drivers under database.connections (since it's a top-level option), you may slim this section to only the drivers you use. For example, if you use the default testing and mysql database drivers but also have a custom mysql_replica driver in Laravel 11, your config/database.php file may be: <?php return [ 'connections' => [ 'mysql_replica' => [ 'driver' => 'mysql', 'url' => env('DB_REPLICA_URL'), 'host' => env('DB_REPLICA_HOST', '127.0.0.1'), 'port' => env('DB_REPLICA_PORT', '3306'), 'database' => env('DB_DATABASE', 'laravel'), 'username' => env('DB_REPLICA_USERNAME', 'root'), 'password' => env('DB_REPLICA_PASSWORD', ''), 'unix_socket' => env('DB_SOCKET', ''), 'charset' => env('DB_CHARSET', 'utf8mb4'), 'collation' => env('DB_COLLATION', 'utf8mb4_0900_ai_ci'), 'prefix' => '', 'prefix_indexes' => true, 'strict' => true, 'engine' => null, 'options' => extension_loaded('pdo_mysql') ? array_filter([ PDO::MYSQL_ATTR_SSL_CA => env('MYSQL_ATTR_SSL_CA'), ]) : [], ], ] ]; Of course, you are welcome to preserve the entire set of default configuration files with all of their options. But if you like Laravel’s new, slimmer application structure and want to reduce the noise in your configuration files to your true customizations, this is the way to go. The post Laravel 11 streamlined configuration files appeared first on Laravel News. Join the Laravel Newsletter to get Laravel articles like this directly in your inbox.

Laravel 11 is now released!
Laravel 11 is now released!

Laravel 11 is now released, including a minimum PHP v8.2, a new Laravel Reverb package, streamlined directory structure, and more... Laravel Reverb Laravel Reverb is a new first-party WebSocket server for Laravel applications, bringing real-time communication between client and server. Some of the features of Reverb include. Blazing Fast Reverb is fine-tuned for speed. A single server can support thousands of connections and piping data without the delay and inefficiency of HTTP polling. Seamless Integration Develop with Laravel's broadcasting capabilities. Deploy with Reverb's first-party Laravel Forge integration. Monitor with baked-in support for Pulse. Built for Scale Infinitely increase capacity by utilizing Reverb's built-in support for horizontal scaling using Redis, allowing you to manage connections and channels across multiple servers. Pusher Reverb utilizes the Pusher protocol for WebSockets, making it immediately compatible with Laravel broadcasting and Laravel Echo. Streamlined Directory Structure <iframe width="560" height="315" src="https://www.youtube.com/embed/lQSEBvxuXiU?si=5wL1B2ntkPoTaEeF" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" allowfullscreen></iframe> On a fresh install, the file count has dropped by ~ 69 files. Nice. Check out our post on this complete new Laravel 11 Directory Structure Controllers no longer extend anything by default. No more middleware directory. Currently, Laravel includes nine middleware and many you would never customize. However, if you do want to customize them, that is moved to the App/ServiceProvider. For example: public function boot(): void { EncryptCookies::except(['some_cookie']); } No more Http/Kernel Most of the things you used to could do in the Kernel you can now do in the Bootstrap/App. return Application::configure() ->withProviders () -›withRouting( web: __DIR__.'/../routes/web.php' commands: __DIR__.'/../routes/console.php', ) ->withMiddleware(function(Middleware Smiddleware) { $middleware->web(append: LaraconMiddleware::class): }) Model casts changes <iframe width="918" height="516" src="https://www.youtube.com/embed/2WDtpAHRCMA" title="Laravel 11 moves the Model Casts from a property to a method" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" allowfullscreen></iframe> Model casts are now defined as a method instead of a property. When defined as a method we can do other things, like call other methods directly from the casts. Here is an example using a new Laravel 11 AsEnumCollection: protected function casts(): array { return [ 'email_verified_at' => 'datetime', 'password' => 'hashed', 'options'=› AsEnumCollection::of(UserOption::class), ]; } New Dumpable Trait This aims to streamline the core of the framework since multiple classes currently have "dd" or "dump" methods. Plus you can use this Dumpable trait in your own classes: class Stringable implements JsonSerializable, ArrayAccess { use Conditionable, Dumpable, Macroable, Tappable; str('foo')->dd(); str('foo')->dump(); Read more about the new Dumpable Trait. Config Changes Laravel has a lot of config files, and Laravel 11 removes these, and all config options cascade down. The .env has been expanded to include all the options you'd want to set. Read more about the config changes. New Once method <iframe width="918" height="516" src="https://www.youtube.com/embed/cZEK0O3CGto" title="Laravel 11 Once Memoization Helper" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" allowfullscreen></iframe> Laravel 11 includes a new once helper method that ensures you'll always get the same value no matter how many times you call an object method. The once function is helpful when you have some code that you want to ensure only ever runs one time. Slimmed default Migrations When you start a new Laravel app, it comes with some default migrations from 2014 and 2019. These now will come with the dates removed and moved into just two files. Watch our Instagram Reel Routes changes By default, there will be only two route files, console.php and web.php. API routes will now become opt-in via php artisan install:api, giving you the API routes file and Laravel Sanctum. The same with websocket broadcasting, php artisan install:broadcasting. New up Health Route <iframe width="568" height="1010" src="https://www.youtube.com/embed/EmvHPg8JpB4" title="New Laravel 11 applications will include a new health /up endpoint. #laravel #laravel11" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" allowfullscreen></iframe> Laravel 11 will include a new /up health route that fires a DiagnosingHealthEvent so you can better integrate with up time monitoring. APP_KEY Rotation <iframe width="1280" height="720" src="https://www.youtube.com/embed/0dJMX9RjW9A" title="Taylor at Laracon EU showing the new APP_KEY rotation features of Laravel 11" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" allowfullscreen></iframe> In older versions of Laravel, if you changed your APP_KEY it could lead to broken data in the database. Laravel 11 has a new graceful rotation which will NOT break old encrypted data, using an APP_PREVIOUS_KEYS comma-delimited list .env variable. It will auto re-encrypt the data using new key. Console Kernel Removed The Console Kernel is being removed, and you'll be able to instead define your console commands right in routes/console.php. Named Arguments Named arguments are not covered by Laravel's backwards compatibility guidelines. They may choose to rename function arguments when necessary in order to improve the Laravel codebase. When calling Laravel methods using named arguments should be done cautiously and with the understanding that the parameter names may change in the future. Eager Load Limit <iframe width="918" height="516" src="https://www.youtube.com/embed/n4oiIa6BDqE" title="Laravel 11 will have native support for limiting the number of eagerly loaded results per parent." frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" allowfullscreen></iframe> Laravel 11 integrates the code behind the "eager load limit" package: User::select('id', 'name')->with([ 'articles' => fn($query) => $query->limit(5) ])->get(); Read more about Eager Load Limit here. New Artisan Commands New Artisan commands have been added to allow the quick creation of classes, enums, interfaces, and traits: php artisan make:class php artisan make:enum php artisan make:interface php artisan make:trait New Welcome Page <iframe width="1280" height="720" src="https://www.youtube.com/embed/ErpVLcxo3cI" title="The history of the Laravel welcome page, including the new one in Laravel 11" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" allowfullscreen></iframe> Along with major updates to Laravel, we'll get a new welcome page when creating a new Laravel application. When will Laravel 11 be released? Laravel 11 will be released on March 12, 2024 PHP 8.2 minimum support This was an early decision, but Laravel 11 apps require a minimum of PHP 8.2. If you are running an older version of PHP, now is a good time to get that upgraded. SQLite 3.35.0+ required If you use a SQLite database, then Laravel 11 will require SQLite 3.35.0 or greater. Doctrine DBAL Removal Laravel is no longer dependent on the Doctrine DBAL and registering custom Doctrines types is no longer necessary for the proper creation and alteration of various column types that previously required custom types. Install Laravel 11 The easiest way to install Laravel 11 is to first set up the Laravel Installer composer global require laravel/installer Then run: laravel new projectname Upgrade to Laravel 11 Laravel Shift is the easiest way to upgrade but you can also follow the upgrade guide in the Laravel docs Laravel Support Policy For all Laravel releases, bug fixes are provided for 18 months and security fixes are provided for 2 years. For all additional libraries, including Lumen, only the latest major release receives bug fixes. Version PHP (*) Release Bug Fixes Until Security Fixes Until Laravel 9 8.0 - 8.2 February 8th, 2022 August 8th, 2023 February 6th, 2024 Laravel 10 8.1 - 8.3 February 14th, 2023 August 6th, 2024 February 4th, 2025 Laravel 11 8.2 - 8.3 March 12th, 2024 September 3rd, 2025 March 12th, 2026 12 8.2 - 8.3 Q1 2025 Q3, 2026 Q1, 2027 Wrapup So far, all these features are considered beta for Laravel 11 and are designed to improve your workflow. Things can and probably change, and we will keep this post updated as new features are announced. The post Laravel 11 is now released! appeared first on Laravel News. Join the Laravel Newsletter to get Laravel articles like this directly in your inbox.

Resources for Getting Up To Speed with Laravel 11
Resources for Getting Up To Speed with Laravel 11

Now that Laravel 11 is out, we wanted to share some resources from the community for getting up-to-speed with Laravel 11. Whether you’re a seasoned Laravel developer or just stepping into the world of web development, we’ve hand-picked some content we think will help you get up to speed quickly: Laravel 11 Highlights in 90 Seconds If you’re already familiar with Laravel, we walk you through Laravel 11 highlights in 90 seconds: <iframe width="560" height="315" src="https://www.youtube.com/embed/f41juaJMxKE?si=-pD8L-jK3TwyJ_41" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" allowfullscreen></iframe> Dive Into the Streamlined Directory Structure in Laravel 11 Our Dive into the Streamlined Directory Structure in Laravel 11 article walks you through the latest Laravel skeleton directory structure when setting up a new Laravel 11 application. <iframe width="560" height="315" src="https://www.youtube.com/embed/lQSEBvxuXiU?si=gstIKUy4OLMao8Bg" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" allowfullscreen></iframe> Welcome to Laravel 11 Over on the official Laravel YouTube channel, Christoph Rumpel walks through new features that landed in this week’s Laravel 11 release: <iframe width="560" height="315" src="https://www.youtube.com/embed/rmMCiP-iVYM?si=2rFDo4jOhx5fVZ6g" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" allowfullscreen></iframe> Laravel 11 is Here by Josh Cirre Josh Cirre’s video Laravel 11 is Here (and I'm so excited) is another excellent roundup of high-level features released with Laravel 11: <iframe width="560" height="315" src="https://www.youtube.com/embed/IEVufZPXzBo?si=fFvV8D37UWnpqB-F" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" allowfullscreen></iframe> Laracasts: 30 Days to Learn Laravel Laracasts has updated their free Laravel course to Laravel 11, 30 Days to Learn Laravel. You’ll learn Laravel from scratch in one month, one video per day, and learn everything you need to start building Laravel apps. This is a free course that anyone can watch! Laravel Reverb Documentation Laravel Reverb, a first-party WebSocket server for Laravel applications, launched with Laravel 11 as well. The full documentation for getting started with Reverb is now available in the official documentation. It will walk you through installing, setting up, and running the Reverb server in production. <iframe width="560" height="315" src="https://www.youtube.com/embed/TkYXIHgdrgA?si=lOlgORQ2yzpFSJ2y" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" allowfullscreen></iframe> The Laravel Reverb website is beautiful, so check it out for a quick overview of Reverb, along with links to the documentation. Upgrade to Laravel 11 with Shift You can automate the Upgrade of Laravel 10.x to Laravel 11.x with Laravel Shift. This is an amazing way to speed up the upgrade process and get those existing Laravel applications running on the latest version of Laravel. Laravel News creator Eric Barnes demonstrates upgrading laravel-news.com to Laravel 11 using the amazing Shift service: <iframe width="560" height="315" src="https://www.youtube.com/embed/Z6aY9FfY5eI?si=9hh-F5U_xj6kB-u2" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" allowfullscreen></iframe> The Laravel 11 shift includes streamlining your configuration files to their true customizations, consolidating service providers, getting your app to reflect the Laravel 11 application structure updates, and more. Check out the Shift demo video for some additional insight. Laravel 11 Documentation Prologue Each Laravel release contains a Prologue section, which contains Release Notes, an Upgrade Guide, and a Contribution Guide. Using Laravel Shift is the best way to upgrade, but reading through the release notes and upgrade guide is an excellent way to familiarize yourself with changes to the latest Laravel version. A quick way to stay current with Laravel releases is the laravelversions.com website (and their APIs) so that you always know where to go to find dates for release, end of bug fixes, and end of security updates for Laravel & PHP. Hat tip to Matt Stauffer, who helps maintain laravelversions.com and phpreleases.com. At the time of release, here’s an updated support policy: Learn More On our Laravel News YouTube channel, we have a Laravel 11 playlist for everything we've published leading up to the release of Laravel 11. We’d love to hear what you’re building with Laravel! The post Resources for Getting Up To Speed with Laravel 11 appeared first on Laravel News. Join the Laravel Newsletter to get Laravel articles like this directly in your inbox.

Statamic announces next Flat Camp retreat (EU edition)
Statamic announces next Flat Camp retreat (EU edition)

Statamic's Flat Camp is an unforgettable, relationship-focused retreat for the Statamic and Laravel community. Happening June 11-14, 2024, and set in the idyllic Italian countryside, right outside Rome, surrounded by beautiful scenery, we talk both business and non-business. Spend time with the gentlemen from the Statamic Core team, meet those lovely people from the community IRL, influence the future roadmap, and talk about operating your freelance or agency business to peers, all while sitting by the pool, having lunch or dinner cooked by a private chef, and more! It's a different experience compared to a regular conference you might have attended in the past. You won't need a hotel since the accommodation is included in the ticket as well. This is all part of the experience. Read the recap of last year's retreat over on the Statamic blog or relive some of the magic by watching the recap video. <iframe width="939" height="528" src="https://www.youtube.com/embed/x1kzmJFGTJA" title="Flat Camp 2023" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" allowfullscreen></iframe> It truly was a unique get-together last year. Still need convincing after watching that recap video? Let Jack, founder of Statamic, tell you why you (and/or your colleagues) should come. <iframe width="939" height="528" src="https://www.youtube.com/embed/RHttx8q1VOk" title="Why you should come to Flat Camp – The Statamic Non-Conf" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" allowfullscreen></iframe> Flat Camp is limited to 50 guests and a ticket includes: 3 Nights lodging in our own private Italian villa Private chef will prepare us breakfast, lunch, and dinner Access to all workshops, intimate talks, and wine cellar chats Exclusive Statamic/Flat Camp swag Other mysteries and surprises For complete details and tickets, head over to the Flat Camp site. The post Statamic announces next Flat Camp retreat (EU edition) appeared first on Laravel News. Join the Laravel Newsletter to get Laravel articles like this directly in your inbox.

Tablar Kit: UI Components for Tablar Admin Dashboards
Tablar Kit: UI Components for Tablar Admin Dashboards

The Tablar Kit package for Laravel adds a UI kit for your Tablar admin dashboard. This UI kit adds many easy-to-use components, making your dashboard more visually appealing and user-friendly. It's all about simplicity and enhancing your experience with Laravel Tablar: Standard Form Components: Includes text fields, radio selections, checkboxes, and secure password inputs, along with datepicker & custom buttons. Tailored for efficient data entry and user interaction. Advanced Dropdown: Includes both standard and dependent Dropdown, suitable for dropdown data relationships. File Upload with On-the-Fly Image Editing: This feature not only simplifies the file uploading process but uniquely offers on-the-fly image editing capabilities, adding a layer of convenience and efficiency to your workflow. Optimized Data Tables with Export Options: The data table component not only organizes and displays information but also enables data export in formats such as CSV, XLS, PDF, and HTML, catering to diverse data analysis and reporting needs. Rich Text Editor with File Upload and Browser Features: Enhance your content creation with an editor that supports seamless file uploads. It includes a file browser feature, ensuring a comprehensive and uninterrupted content creation process. Responsive and Customizable Design: Each component in the Tablar Kit is built to be fully responsive, ensuring compatibility with various screen sizes. Moreover, customization options abound, allowing you to align each component with your application's theme, including support for dark mode. The Tablar UI Kit provides Laravel Blade components and the required JavaScript code for components to function. For example, you can easily add date pickers, file uploads, WYSIWYG editors, and more using premade components to your Tablar dashboards: {{-- Datepickers --}} <x-flat-picker name="admission_date"></x-flat-picker> <x-lite-picker name="admission_date"></x-lite-picker> {{-- File uploader --}} <x-filepond name="profile_image"/> {{-- Jodit editor (https://xdsoft.net/jodit/) --}} <x-jodit name="editor"></x-jodit> {{-- More at https://tablar.ebuz.xyz/docs/11.0/components --}} You can learn more about this package, get full installation instructions, and view the source code on GitHub. Also, you can view the Tablar Kit documentation to get familiar with the UI components. This package requires the Tablar Laravel Admin Template, which you can learn about here. The post Tablar Kit: UI Components for Tablar Admin Dashboards appeared first on Laravel News. Join the Laravel Newsletter to get Laravel articles like this directly in your inbox.

Easily create complex database queries with the Query Enrich Package
Easily create complex database queries with the Query Enrich Package

Laravel Query Enrich is designed to easily create complex database queries in Laravel without having to write complicated SQL code. Here are some examples taken from the readme: Example of fetching orders placed in the last 7 days With Laravel Query Enrich $recentOrders = DB::table('orders') ->where(c('created_at'), '>=', QE::subDate(QE::now(), 7, Unit::DAY)) ->get(); Without Laravel Query Enrich $recentOrders = DB::table('orders') ->whereRaw('created_at >= NOW() - INTERVAL ? DAY', 7) ->get(); Raw Query SELECT * FROM `orders` WHERE `created_at` >= NOW() - INTERVAL 7 DAY; Using the avg function for grabbing the average monthly price for oil and gas With Laravel Query Enrich $monthlyPrices = DB::table('prices') ->select( QE::avg(c('oil'))->as('oil'), QE::avg(c('gas'))->as('gas'), 'month' ) ->groupBy('month') ->get(); Without Laravel Query Enrich $monthlyPrices = DB::table('prices') ->select(DB::raw('avg(`oil`) as `oil`, avg(`gas`) as `gas`, `month`')) ->groupBy('month') ->get(); Raw Query select avg(`oil`) as `oil`, avg(`gas`) as `gas`, `month` from `prices` group by `month` Using an exists query With Laravel Query Enrich $authors = DB::table('authors')->select( 'id', 'first_name', 'last_name', QE::exists( Db::table('books')->where('books.author_id', c('authors.id')) )->as('has_book') )->orderBy( 'authors.id' )->get(); Without Laravel Query Enrich $authors = DB::table('authors') ->select( 'id', 'first_name', 'last_name', DB::raw('exists(select * from `books` where `books`.`author_id` = `authors`.`id`) as `has_book`')) ->orderBy( 'authors.id', ) ->get(); Raw Query select `id`, `first_name`, `last_name`, exists(select * from `books` where `books`.`author_id` = `authors`.`id`) as `result` from `authors` order by `authors`.`id` asc Getting a full name using concatws With Laravel Query Enrich $authors = Author::select( 'first_name', 'last_name', QE::concatWS(' ', c('first_name'), c('last_name'))->as('result') )->get(); Without Laravel Query Enrich $author = Author::select( 'first_name', 'last_name', DB::raw("concat_ws(' ', `first_name`, `last_name`) as `result`") )->first(); Raw Query select `first_name`, `last_name`, concat_ws(' ', `first_name`, `last_name`) as `result` from `authors` Check out the documentation for complete details and view the package on Github. The post Easily create complex database queries with the Query Enrich Package appeared first on Laravel News. Join the Laravel Newsletter to get Laravel articles like this directly in your inbox.

Introducing the Context Facade in Laravel
Introducing the Context Facade in Laravel

Laravel added a new Context service to define contextual data to the current request. Context data is included in all log entries for that request, and queued jobs will also retain that same data. Using contextual data allows you to easily trace back code execution for a given request and any distributed flows in your application: // In a middleware... Context::add('hostname', gethostname()); Context::add('trace_id', (string) Str::uuid()); // In a controller... Log::info('Retrieving commit messages for repository [{repository}].', [ 'repository' => $repo, ]); Http::get('https://github.com/...'); /* Log entry example: [2024-01-19 04:20:06] production.INFO: Retrieving commit messages for repository [laravel/framework]. {"repository":"laravel/framework"} {"hostname":"prod-web-1","trace_id":"a158c456-d277-4214-badd-0f4c8e84df79"} */ Contextual data also supports concepts like stacks, where you can push data to the same context, effectively appending data: Event::listen(function (JobQueued $event) { Context::push('queued_job_history', "Job queued: {$event->job->displayName()}"); }); Context::get('queued_job_history'); // [ // "Job queued: App\Jobs\MyFirstJob", // "Job queued: App\Jobs\MySecondJob", // "Job queued: App\Jobs\MyThirdJob", // ] If you'd like to learn more about this feature, check out the Pull Request description. Hat tip to Tim MacDonald, who created this feature for the framework! The post Introducing the Context Facade in Laravel appeared first on Laravel News. Join the Laravel Newsletter to get Laravel articles like this directly in your inbox.