#laravel valet function
Explore tagged Tumblr posts
apptagsolution · 1 year ago
Text
Exploring Essential Laravel Development Tools for Building Powerful Web Applications
Laravel has emerged as one of the most popular PHP frameworks, providing builders a sturdy and green platform for building net packages. Central to the fulfillment of Laravel tasks are the development tools that streamline the improvement process, decorate productiveness, and make certain code quality. In this article, we will delve into the best Laravel development tools that each developer should be acquainted with.
1  Composer: Composer is a dependency manager for PHP that allows you to declare the libraries your project relies upon on and manages them for you. Laravel itself relies closely on Composer for package deal management, making it an essential device for Laravel builders. With Composer, you may without problems upload, eliminate, or update applications, making sure that your Laravel project stays up-to-date with the present day dependencies.
2  Artisan: Artisan is the command-line interface blanketed with Laravel, presenting various helpful instructions for scaffolding, handling migrations, producing controllers, models, and plenty extra. Laravel builders leverage Artisan to automate repetitive tasks and streamline improvement workflows, thereby growing efficiency and productiveness.
3  Laravel Debugbar: Debugging is an crucial component of software program development, and Laravel Debugbar simplifies the debugging procedure by using supplying exact insights into the application's overall performance, queries, views, and greater. It's a accessible device for identifying and resolving problems all through improvement, making sure the clean functioning of your Laravel application.
4  Laravel Telescope: Similar to Laravel Debugbar, Laravel Telescope is a debugging assistant for Laravel programs, presenting actual-time insights into requests, exceptions, database queries, and greater. With its intuitive dashboard, developers can monitor the software's behavior, pick out performance bottlenecks, and optimize hence.
5  Laravel Mix: Laravel Mix offers a fluent API for outlining webpack build steps on your Laravel application. It simplifies asset compilation and preprocessing duties together with compiling SASS or LESS documents, concatenating and minifying JavaScript documents, and dealing with versioning. Laravel Mix significantly streamlines the frontend improvement procedure, permitting builders to attention on building notable consumer reviews.
6  Laravel Horizon: Laravel Horizon is a dashboard and configuration system for Laravel's Redis queue, imparting insights into process throughput, runtime metrics, and more. It enables builders to monitor and control queued jobs efficiently, ensuring most beneficial performance and scalability for Laravel programs that leverage history processing.
7  Laravel Envoyer: Laravel Envoyer is a deployment tool designed specifically for Laravel packages, facilitating seamless deployment workflows with 0 downtime. It automates the deployment process, from pushing code adjustments to more than one servers to executing deployment scripts, thereby minimizing the chance of errors and ensuring smooth deployments.
8  Laravel Dusk: Laravel Dusk is an cease-to-give up browser testing tool for Laravel applications, built on pinnacle of the ChromeDriver and WebDriverIO. It lets in builders to put in writing expressive and dependable browser assessments, making sure that critical user interactions and workflows function as expected across exceptional browsers and environments.
9  Laravel Valet: Laravel Valet gives a light-weight improvement surroundings for Laravel applications on macOS, offering seamless integration with equipment like MySQL, NGINX, and PHP. It simplifies the setup process, permitting developers to consciousness on writing code instead of configuring their development environment.
In end, mastering the vital Laravel development tools noted above is important for building robust, green, and scalable internet packages with Laravel. Whether it's handling dependencies, debugging troubles, optimizing overall performance, or streamlining deployment workflows, those equipment empower Laravel developers to supply outstanding answers that meet the demands of current internet development. Embracing these gear will certainly increase your Laravel improvement enjoy and accelerate your journey toward turning into a talented Laravel developer.
3 notes · View notes
maveninfo979 · 2 years ago
Text
Django vs. Laravel: Unveiling the Battle of Web Development Frameworks
In the dynamic world of web development, choosing the right framework is crucial for building robust and scalable applications. Two contenders that have garnered significant attention are Django and Laravel. In this blog post, we'll delve into the strengths and features of both frameworks to help you make an informed decision. Additionally, we'll explore the landscape of Laravel web development services in the Netherlands, emphasizing the presence of expert Laravel development companies in the region.
Tumblr media
Django: The Pythonic Elegance
Django, the high-level Python web framework, has gained a reputation for its simplicity, versatility, and scalability. Here are some key features that make Django stand out:
Batteries Included: Django follows the "batteries included" philosophy, offering a comprehensive set of tools, libraries, and functionalities out of the box. This reduces the need for external dependencies and simplifies development.
DRY (Don't Repeat Yourself) Principle: Django emphasizes code reusability, following the DRY principle. This results in cleaner, more maintainable code, making it an ideal choice for developers who value efficiency.
ORM (Object-Relational Mapping): The built-in ORM simplifies database operations, allowing developers to interact with the database using Python code. This abstraction enhances productivity and reduces the complexity of database-related tasks.
Laravel: The PHP Powerhouse
Laravel, a PHP web application framework, has gained popularity for its elegant syntax, developer-friendly features, and modern development practices. Here are some compelling aspects of Laravel:
Eloquent ORM: Laravel's Eloquent ORM simplifies database operations and offers an intuitive syntax for interacting with databases. It enables developers to work with databases using expressive and eloquent code.
Blade Templating Engine: Laravel's Blade templating engine provides an elegant syntax for designing templates, making it easy to create dynamic and engaging user interfaces. It enhances code readability and speeds up the development process.
Laravel Ecosystem: Laravel boasts a robust ecosystem with features like Laravel Mix for asset compilation, Laravel Horizon for managing queues, and Laravel Valet for local development. This ecosystem contributes to the framework's versatility.
Laravel Web Development in the Netherlands: A Growing Trend
As businesses in the Netherlands strive to leverage the power of Laravel for their web development needs, the presence of expert Laravel development companies has become increasingly significant. These companies offer a range of Laravel web development services tailored to meet the diverse requirements of clients.
1. Laravel Development Company Netherlands: Crafting Digital Excellence
Explore the services offered by leading Laravel development companies in the Netherlands. These companies are adept at harnessing the power of Laravel to build scalable, secure, and feature-rich web applications.
2. Laravel Web Development Service Netherlands: Elevating Digital Experiences
Highlight the specific Laravel web development services offered by these companies, such as custom application development, API development, and Laravel-based e-commerce solutions. Discuss how these services contribute to elevating digital experiences for businesses.
3. Laravel Netherlands: A Hub of Innovation
Conclude by emphasizing the dynamic and innovative landscape of Laravel development in the Netherlands. Showcase success stories, projects, and the overall impact of Laravel on the digital transformation journey of businesses in the region.
Conclusion: Django or Laravel? The Choice is Yours!
In the Django vs. Laravel debate, the ultimate choice depends on your specific project requirements, development preferences, and the expertise of your development team. Both frameworks offer unique advantages, and the thriving Laravel development scene in the Netherlands presents exciting opportunities for businesses seeking top-notch web solutions. Whether you opt for the Pythonic elegance of Django or the PHP powerhouse of Laravel, the goal is to create digital experiences that resonate with your audience and drive business success.
0 notes
programmerandcoder · 5 years ago
Link
Tumblr media
Laravel Valet Function - Learn How to Use?
0 notes
katyslemon · 3 years ago
Text
Ultimate Guide on How to Outsource Laravel Development
Introduction
Before speaking about outsourcing Laravel, how about we discuss regarding its popularity first? Laravel has drawn considerable attention as a framework for web and app development over the years. No doubt, it’s because of its extensive set of cutting-edge features and built-in functionality.
I am assuming that you are already familiar with why Laravel is an open-source PHP framework introduced in 2011. Today, it is used to create modern websites and web apps. Laravel is one of the best PHP frameworks for delivering functionality and performance today while making web and app development easier.
If you’re still on the fence about using Laravel for your next project, take a look at the guide below. Continue reading if you are looking for a talented Laravel developer for your next project and wondering HOW! This is an ultimate guide on when, why, and how to outsource Laravel development.
When Should You Consider Outsourcing Laravel development?
Laravel’s syntax is exquisite and expressive. Speaking of the web app development process, it is designed to be easy and rewarding. Let’s see where Laravel development services are used or when you should consider Outsourcing Laravel development.
Companies Dealing in Data Management and Backend:
Content-oriented app development and CRM platforms are two fine examples of this. There are two options: Either use the Laravel framework to integrate with an existing CMS, or build one from the ground up with scalability in mind.
Enterprise-level Apps:
These are obviously required by businesses. This includes industries like media, healthcare, eCommerce, and others with high-traffic websites that require data processing. Event Broadcasting, Service Container, backed-in systems, and a slew of other features make Laravel more seamless and smooth than other PHP frameworks.
Beginners and Startups:
Laravel appears to be a quick, powerful, understandable, and accessible framework for young web developers. It has a large developer community, educational projects like free/comprehensive tutorials, Laracasts, and other useful tools like Lumen, Spark, Vapor, Valet, and others.
Business Development:
Laravel is a good scalability option for small and medium-sized businesses due to its microservices architecture. As a result, creating a website with immediate updates becomes a reality.
Outsourcing and Outstaffing:
These are another two options. The majority of software development companies, including PHP development, are outsourced. However, the global Laravel outsourcing market is expected to grow, and Laravel is destined to become more popular.
Infrastructure for IoT:
The answer to the question of whether PHP and IoT have a future together is “yes.” Many Laravel app development companies recognize the framework’s potential in the coming years, and certainly now.
Read more for Outsource Laravel Development
0 notes
magicalengineershark · 4 years ago
Text
A synopsis of the Laravel Framework Ecosystem
Are you familiar with Laravel, one of the popular PHP frameworks? Although it is not a new name in the web development world, a professional Laravel developer always looks for a chance to refine his development process. Now, we are going to introduce you to Laravel tools and bundles. As Laravel Framework offers lots of potentials to polish the code quality, it is better to learn about its feature-rich ecosystem.
Basics about Laravel Framework
Laravel has turned out to be one the most accepted frameworks for its high scalability, speed, intuitiveness, and cost-effectiveness. Moreover, Laravel ecosystem ensures strong security with features, like active user checking, encryption, BCrypt hashing, and password reset.
While Laravel is an uncomplicated MVC framework, it has a robust design, created for PHP application development. Thus, due to the rich functionality, Laravel enables us to optimize our web development processes.
What benefits do you get choosing Laravel framework for application development?
Let us have a look at the benefits-
High-end     performance
What’s the major trait of a quality application? It must perform flawlessly all the time. With Laravel, it is easy to develop a high-performing web application.
Security
Security is another concern related to a business application. By using Laravel, developers can save your app from digital threats. It makes sure that the web application will function smoothly with no security risk.
Time-saving     and cost-saving solution
MVC framework of Laravel helps in the rapid development of web applications. As a Laravel development company minimizes the development time, it can reduce the overall charge.
Detailed     verification
Unauthentic users must not access your valuable resources. To ensure it, verification is the best option. Thus, Laravel keeps your application secure and prevent unauthentic clients from using your resources.
A     list of amazing features
Impressive features are one of the reasons distinguishing Laravel from other PHP-based frameworks. Besides, professional developers can offer you high-class web applications that will deliver an increasing ROI for your business.
Laravel Ecosystems
The dynamic ecosystem is increasing its maturity, and it reveals its potential to manage any use case. Therefore, let us have a look at the best Laravel ecosystems available for different purposes.
Laravel     Nova- To increase your productivity
It is a uniquely designed, sleek-looking single-page application. Laravel developers have designed this administration panel. Besides, with simple PHP coding, the Nova dashboard is configurable.
The most notable things of Nova are-
Resource Management– A CRUD interface of Nova is best for Eloquent models. Nova works with different Eloquent relationships, and also you may adjust the polymorphic data.
Actions– They refer to PHP tasks, running against resources. Also, there are queued actions on the Nova dashboard.
Filters– For resource indexes, you can compose custom filters to let users have a view at different data segments. You may also use the integrated filters.
Lenses– You may think of having more customizations for the resource list. Thus, insert lenses to the resource to control the Eloquent query.
Metrics– Laravel Nova has simplified the process of displaying custom metrics for the application. You can create graphs of different types within a few seconds.
Authorization– The current authorization policies of Laravel integrate Nova. Moreover, Nova resources help in leveraging your application policies to identify the user’s abilities.
Custom Fields– Rely on the Nova CLI to find a field type, not originally present in Nova. Hence, you can design and implement this field very easily.
Laravel     Horizon- Best queue manager
When you have chosen the Laravel environment for projects, you may rely on Horizon for queue management. The overall configuration is very easy, and it gives you control over Redis queues. Besides, it is one of the Laravel tools helping professional developers to monitor and configure the queue processing.
Moreover, Laravel Horizon enables web designers to create beautiful User Interface. This system is available at free of cost. Besides, the open-source developers choose this framework for their purpose.
Laravel     Lumen- Faster development of microservices
Lumen is popular as one of the microframework effective for the development of microservices with Laravel. To say simply, it is the fastest and most lightweight Laravel framework version.
Moreover, components of Lumen are similar to that of Laravel. It gives you convenience while adding the power to the major framework. Furthermore, it ensures better response time to boosts the speed and performance standard of the related components.
However, it does not work with other Laravel libraries, including Scout and Cashier. Laravel Lumen is help for creating smaller components.
Laravel     Shift for automatic upgrades
Professionals may need automation for the upgrade process in their Laravel development projects. In that case, Shift comes as the best solution. Besides, it is really easy to update Laravel apps using Shift.
By logging in to Bitbucket or GitHub account, developers can buy their upgrade packages and add the Laravel Shift account as one of the collaborators.
Laravel     Spark- Best for SaaS projects
Spark is one of the parts of the Laravel package, helpful SaaS application developers. Its major aim is to streamline the scaffolding process for invoicing systems. Additionally, Spark works best for user management, as it features different options like password resets, authentication, invoicing, and subscription billing.
Furthermore, the team of developers will get more time to work on the application functionalities. Thus, they can save time to deal with complicated elements, used repeated for SaaS applications.
Know about Laravel development environment
You can find two major Laravel development environments. One of them works locally on Mac, while another one is the pre-packed Vagrant box.
Laravel     Valet
Valet ensures a quick start for macOS users. Developers need to select a directory where they have parked their projects.
Laravel     Homestead
It is another development environment, not restricted only to macOS. However, it also works with Windows and Linux systems. Besides, it comprises PHP 7.1, Git, Node, and Composer.
Features that have made Laravel a distinguished framework
Template     Engine
Laravel is a unique framework, offering innovative and lightweight templates. Thus, Laravel application developers are capable of creating the most intriguing design for the interface. To develop it, Laravel professionals rely on the dynamic content seeding process and use Laravel widgets.
Unit     Testing
It is a useful feature to assess the web application feature. Besides, with the unit testing process by using the PHP Unit, developers accomplish this task.
Artisan
Artisan is one of the inbuilt tools for developers. Also, this Laravel tool reduces the time needed for complicated programming tasks.
Database     Migration
The ability to share databases is another advantageous thing for a team of developers. Laravel makes it easy to migrate the database.
Caching
The caching system of Laravel helps to store objects in a file. Moreover, it ensures smooth integration of a web framework with any other caching system, like Redis, APC, and Memcached.
We have mentioned only some of the tools of the big Laravel ecosystem. Laravel development professionals have found increasing popularity of the framework in the past few years. Thus, it is another reason for releasing several Laravel tools. The developers always stay updated with new packages to speed up their application development process. Furthermore, they use the Laravel community as one of the biggest assets. Therefore, look for a Laravel application development agency and get the best services from developers.
1 note · View note
concettolabs · 4 years ago
Text
The Trend Of Laravel Application Development Will Never End!
Tumblr media
We all can say that PHP is considered a “Low-barrier-to-entry” programming language. Though there are many arguments against it. But it is still among the list of top 10 most used programming languages all over the world. Also, it is the most popular language for making clean, fast, and reliable Laravel application development. And, we are the ones who can be a great partner as a PHP development company.
Nowadays, people don’t start working with any software development quickly. Only by knowing the core of the programming language, they don’t start. They took part in gaining some frameworks and library work. Because they are designed as the more basic structure of any app development. If we talk about the web project built on PHP. Then, Laravel is the most preferable framework for web app development. Through this article, we will get some detailed knowledge. And, know how Laravel development services work. and trends. Added, we will check out the key features as well.
What are the key features of Laravel?
In 2020, Laravel came up with a new recognition which can be said as the entire ecosystem developed on PHP. Yes, it is not only a simple, reliable, and popular PHP framework. We can consider it as a whole ecosystem. It was developed in 2011 and declared as open-source. Also, considerably established with the consideration of MVC architecture. It is known for authentication, routing, caching, and many other tasks. One can create different layouts, unit testing, and Bcrypt hashing using Laravel.
Let’s have some insights on the salient features of Laravel
Tumblr media
You get MVC support
High-security level
Object-oriented library
It is a Simple Restful routing process
Async queue existence for performing long-term tasks
Consistent updates
Flawless database migration
Effective third-party integration
Laravel Development Trends
We all know that web app development is shaped in a smooth and complete process. The syntax of the Laravel framework comes out as an elegant and expressive one. Now, let’s see where our hire Laravel development services can be used.
1. Businesses Requiring Enterprise-Level Apps: This includes healthcare, media, eCommerce, and others. All get heavy traffic on their web pages. They need high data processing. Here, Laravel fulfills this need effectively in comparison with other PHP frameworks. It has been possible due to service containers, backed-in systems, even broadcasting, and much more.
2. Growing Business: Laravel has microservices architecture. Thus, it is good for small and medium-sized businesses’ scalability. Thus, it is possible to create a website pursuing immediate amendments.
3. IoT infrastructure: Yes, PHP and IoT have a future together. Many PHP development companies are aware of this potential framework. And, in upcoming years, it is going to happen for sure.
4. Pre-Built Apps: Currently, time and money both matters the most when you create web apps. So, the good news is, Laravel has introduced many pre-built apps. If you are in need to create a very similar kind of app. Use the templated from the Laravel website.
5. Outsourcing and Outstanding: We have seen many companies be outsourced. And, PHP development is not an exception. We all know that the global outsourcing market is developing. Thus, we cannot deny that Laravel is going to get a huge attraction.
Related:
Why choose the Laravel PHP Framework for Enterprise Web Applications?
6. Backend Data management: This includes content-oriented apps development and CRM platforms. There are two paths: either create one from the base and ensuring scalability. And, the other is to use the Laravel framework integration with existing CMS.
7. Start-ups and Beginners: Being a young web application developer. Laravel seems to be an accessible, quick, powerful, and comprehensible framework. It has a huge development community. You can get free tutorials and handy tools to educate and get comfortable with Laravel. Let’s say, Vapor, Spark, Valet, Lumen, etc.
8. Apps Presupposing Microservice Architecture: When it comes to eCommerce, We mention Microservice architecture. It generally includes several functioning modules. Later, make up a single app with high performance and scalability. All can reach through the built-in Lumen Framework.
9. High-Level Security App: As we discussed, Laravel is a highly secure framework. It does what it claims. We all are aware of the predominant feature of any app, it is security. And, with help of secret words, arranged SQL, and Bcrypt hashing calculation we can do it.
10. Serverless Deployment: Laravel is the platform that allows serverless deployment. By using Vapor, it is possible to create, manage, scale, and restore the databases. All happens from the in-built dashboard.
Does it provide any extra support for the Testing environment?
Yes, it enables an automated testing environment. To get highly accurate results compared to manual testing. Every developer wants to ensure the standards of the application they have developed. They want it to be glitch and bug-free. Here, the ultimate goal is to deliver the best.
Now, Laravel is built in a way to support testing. It helps with testing with PHPUnit and phpunit.xml files for your application. This framework also supports several important helper methods. It aimed at testing for your web applications.
Summary
Laravel is a simple framework to create an application with Laravel. The code is very easily stable and straightforward. Don’t forget to consider Laravel for your next PHP application development. For more detailed information and to start with your app, do connect with us at Concetto Labs. Hire PHP developer from the topmost Laravel development company.
0 notes
optisolbusinesssolution · 5 years ago
Text
Laravel Ecosystem – An Overview
For Free consultation or demo
Laravel is the most happening framework these days. Some of its great features are the intuitiveness, speed, scalability, and high cost-effectiveness. As per the survey report by Enlyft, Laravel is most popular in the United States. The Laravel ecosystem provides powerful security features, such as checking active users, BCrypt hashing, password reset, and encryption, within the framework.
Laravel is a simple yet robust model-view-controller (MVC) framework created for PHP web application development. It became one of the most popular PHP framework thanks to the rich set of functionalities that optimize the development process. Laravel environment facilitates fast development cycles and so delivers the business value relatively quickly. The Laravel brand offers two development environments, one runs locally on your Machine and one is a pre-packaged Vagrant box that has virtually everything you need.
Tumblr media
Development Environment:
Laravel Valet configures the Mac to always run Nginx in the background when the machine starts. Then, using DnsMasq, Valet proxies all requests on the *. test domain to point to sites installed on the local machine.
Laravel Homestead is the official Laravel development environment. Powered by Vagrant, Homestead gets your entire team on the same page with the latest PHP, MySQL, Postgres, Redis, and more.
Packages and tools:
Laravel Passport is native OAuth 2 server for Laravel apps. Like Cashier and Scout, you’ll bring it into your app with Composer. It uses the League OAuth2 Server package as a dependency but provides a simple, easy-to-learn and easy-to-implement syntax.
Laravel Scout provides a simple, driver-based solution for adding a full-text search to the Eloquent models. Using model observers, Scout will automatically keep the search indexes in sync with the Eloquent records.
Laravel Dusk provides an expressive, easy-to-use browser automation and testing API. Dusk is an end-to-end browser testing tool for JavaScript enabled applications. It can work with any Selenium browser, but it comes with ChromeDriver by default which will save you from installing JDK or Selenium.
Laravel Socialite provides an expressive, fluent interface to OAuth authentication with Facebook, Twitter, Google, LinkedIn, GitHub, GitLab, and Bitbucket.
Laravel Echo is a JavaScript library that makes it painless to subscribe to channels and listen for events broadcast by Laravel. Laravel Echo is a tool that makes it easy for you to bring the power of WebSockets to your Laravel applications.
Laravel Mix is a tool for compiling and optimizing assets in a Laravel app. It’s similar to a build tool like gulp, Grunt and such like. it’s specific to Laravel but can also be used externally as an npm package. Laravel Mix covered 80% of Webpack’s use case to make compiling assets easier.
Laravel Cashier provides an expressive, fluent interface to Stripe’s and Braintree’s subscription billing services. In addition to basic subscription management, Cashier can handle coupons, swapping subscription, subscription “quantities”, cancellation grace periods, and even generate invoice PDFs.
Laravel Envoy provides you a simple and elegant way to run common tasks on your remote servers. If you have ever used Fabric, Capistrano or other tools for managing remote tasks, you already have an idea of how Envoy tasks will look like.
Paid tools and services:
Laravel Forge is a tool for deploying and configuring web applications. It was developed by the makers of the Laravel framework, but it can be used to automate the deployment of any web application that uses a PHP server.
Laravel Envoyer is a zero-downtime deployer for PHP & Laravel projects, which means it is a tool that you connect to your server to run your deploys, and which uses a series of tools to ensure that all of the preparation work each deploy needs in order to run.
Laravel Spark is designed with only one goal in mind, to make scaffolding out a billing system for a SaaS app easy.  It features team management, user roles, recurring billing through Stripe, and much more.
Laravel is an optimal solution not only for developing new business ideas but also for existing projects that can shift from their previous frameworks thanks to relatively low barriers to entry. Being up to date with the new tools and packages speeds up the development process, and optimizes the quality of the projects. According to the BuiltWith report, worldwide 150,496 live websites are currently using Laravel.
Do you have a project in your mind and want to do it using the Laravel web framework? Are you looking to hire Laravel developers and experts? We are here to help you out. Contact us at [email protected]
0 notes
mbaljeetsingh · 8 years ago
Text
Writing Custom Laravel Artisan Commands
Laravel Tutorials / August 08, 2017
Writing Custom Laravel Artisan Commands
I’ve written console commands in many different languages, including Node.js, Golang, PHP, and straight up bash. In my experience, the Symfony console component is one of the best-built console libraries in existence—in any language.
Laravel’s artisan command line interface (CLI) extends Symfony’s Console component, with some added conveniences and shortcuts. Follow along if you want to learn how to create some kick-butt custom commands for your Laravel applications.
Overview
Laravel ships with a bunch of commands that aim to make your life as a developer easier. From generating models, controllers, middleware, test cases, and many other types of files for the framework.
The base Laravel framework Command extends the Symfony Command class.
Without Laravel’s console features, creating a Symfony console project is pretty straightforward:
#!/usr/bin/env php <?php // application.php require __DIR__.'/vendor/autoload.php'; use Symfony\Component\Console\Application; $application = new Application(); // ... register commands $application->add(new GenerateAdminCommand()); $application->run();
You would benefit from going through the Symfony console component documentation, specifically creating a command. The Symfony console component handles all the pain of defining your CLI arguments, options, output, questions, prompts, and helpful information.
Laravel is getting base functionality from the console component, and extends a beautiful abstraction layer that makes the building consoles even more convenient.
Combine the Symfony console with the ability to create a shippable phar archive—like composer does—and you have a powerful command line tool at your disposal.
Setup
Now that you have quick intro and background of the console in Laravel let’s walk through creating a custom command for Laravel. We’ll build a console command that runs a health check against your Laravel application every minute to verify uptime.
I am not suggesting you ditch your uptime services, but I am suggesting that artisan makes it super easy to build a quick-and-dirty health monitor straight out of the box that we can use as a concrete example of a custom command.
An uptime checker is just one example of what you can do with your consoles. You can build developer-specific consoles that help developers be more productive in your application and production-ready commands that perform repetitive and automated jobs.
Alright, let’s create a new Laravel project with the composer CLI. You can use the Laravel installer as well, but we’ll use composer.
composer create-project laravel/laravel:~5.4 cli-demo cd cli-demo/ # only link if you are using Laravel valet valet link composer require fabpot/goutte
Do you want to know what the beauty of that composer command was? You just used a project that relies on the Symfony console. I also required the Goutte HTTP client that we will use to verify uptime.
Registering the Command
Now that you have a new project, we will create a custom command and register it with the console. You can do so through a closure in the routes/console.php file, or by registering the command in the app/Console/Kernel.php file’s protected $commands property. Think of the former as a Closure-based route and the latter as a controller.
We will create a custom command class and register it with the Console’s Kernel class. Artisan has a built-in command to create a console class called make:command:
php artisan make:command HealthcheckCommand
This command creates a class in the app/Console/Commands/HeathcheckCommand.php file. If you open the file, you will see the $signature and the $description properties, and a handle() method that is the body of your console command.
Adjust the file to have the following name and description:
<?php namespace App\Console\Commands; use Illuminate\Console\Command; class HealthcheckCommand extends Command { /** * The name and signature of the console command. * * @var string */ protected $signature = 'healthcheck {url : The URL to check} {status=200 : The expected status code}'; /** * The console command description. * * @var string */ protected $description = 'Runs an HTTP healthcheck to verify the endpoint is available'; /** * Create a new command instance. * * @return void */ public function __construct() { parent::__construct(); } /** * Execute the console command. * * @return mixed */ public function handle() { // } }
Register the command in the app/Console/Kernel.php file:
protected $commands = [ Commands\HealthcheckCommand::class, ];
If you run php artisan help healthcheck you should see something like the following:
Setting up the HTTP Client Service
You should aim to make your console commands “light” and defer to application services to accomplish your tasks. The artisan CLI has access to the service container to inject services, which will allow us to inject an HTTP client in the constructor of our command from a service.
In the app/Providers/AppServiceProvider.php file, add the following to the register method to create an HTTP service:
// app/Providers/AppServiceProvider.php public function register() { $this->app->singleton(\Goutte\Client::class, function ($app) { $client = new \Goutte\Client(); $client->setClient(new \GuzzleHttp\Client([ 'timeout' => 20, 'allow_redirects' => false, ])); return $client; }); }
We set up the Goutte HTTP crawler and set the underlying Guzzle client with a few options. We set a timeout (that you could make configurable) and we don’t want to allow the client to follow redirects. We want to know the real status of an HTTP endpoint.
Next, update the HealthcheckCommand::__construct() method with the service you just defined. When Laravel constructs the console command, the dependency will be resolved out of the service container automatically:
use Goutte\Client; // ... /** * Create a new command instance. * * @return void */ public function __construct(Client $client) { parent::__construct(); $this->client = $client; }
The Health Check Command Body
The last method in the HealthcheckCommand class is the handle() method, which is the body of the command. We will get the {url} argument and status code to check that the URL returns the expected HTTP status c
Let’s flesh out a simple command to verify a healthcheck:
/** * Execute the console command. * * @return mixed */ public function handle() { $url = $this->getUrl(); $expected = (int) $this->option('status'); try { $crawler = $this->client->request('GET', $url); $status = $this->client->getResponse()->getStatus(); } catch (\Exception $e) { $this->error("Healthcheck failed for $url with an exception"); $this->error($e->getMessage()); return 2; } if ($status !== $expected) { $this->error("Healthcheck failed for $url with a status of '$status' (expected '$expected')"); return 1; } $this->info("Healthcheck passed for $url!"); return 0; } private function getUrl() { $url = $this->argument('url'); if (! filter_var($url, FILTER_VALIDATE_URL)) { throw new \Exception("Invalid URL '$url'"); } return $url; }
First, we validate the URL argument and throw an exception if the URL isn’t valid. Next, we make an HTTP request to the URL and compare the expected status code to the actual response.
You could get even fancier with the HTTP client and crawl the page to verify status by checking for an HTML element, but we just check for an HTTP status code in this example. Feel free to play around with it on your own and expand on the healthcheck.
If an exception happens, we return a different status code for exceptions coming from the HTTP client. Finally, we return a 1 exit code if the HTTP status isn’t valid.
Let’s test out our command. If you recall, I linked my project with valet link:
$ php artisan healthcheck http://cli-demo.dev Healthcheck passed! $ php artisan healthcheck http://ift.tt/2vB3W2f Healthcheck failed with a status of '404' (expected '200') $ echo $? 1
The healthcheck is working as expected. Note that the second command that fails returns an exit code of 1. In the next section, we’ll learn how to run our command on a schedule, and we will force a failure by shutting down valet.
Running Custom Commands on a Schedule
Now that we have a basic command, we are going to hook it up on a scheduler to monitor the status of an endpoint every minute. If you are new to Laravel, the Console Kernel allows you to run Artisan commands on a schedule with a nice fluent API. The scheduler runs every minute and checks to see if any commands need to run.
Let’s set up this command to run every minute:
protected function schedule(Schedule $schedule) { $schedule->command( sprintf('healthcheck %s', url('/')) ) ->everyMinute() ->appendOutputTo(storage_path('logs/healthcheck.log')); }
In the schedule method, we are running the command every minute and sending the output to a storage/logs/healthcheck.log file so we can visually see the results of our commands. Take note that the scheduler has both an appendOutputTo() method and a sendOutputTo() method. The latter will overwrite the output every time the command runs, and the former will continue to append new items.
Before we run this, we need to adjust the URL. By default, the url('/') function will probably return http://localhost unless you’ve updated the .env file already. Let’s do so now so we can fully test out the healthcheck against our app:
# .env file APP_URL=http://cli-demo.dev
Running the Scheduler Manually
We are going to simulate running the scheduler on a cron that runs every minute with bash. Open a new tab so you can keep it in the foreground and run the following infinite while loop:
while true; do php artisan schedule:run; sleep 60; done
If you are watching the healthcheck.log file, you will start to see output like this every sixty seconds:
tail -f storage/logs/healthcheck.log Healthcheck passed for http://cli-demo.dev! Healthcheck passed for http://cli-demo.dev! Healthcheck passed for http://cli-demo.dev!
If you are following along with Valet, let’s shut it down, so the scheduler fails. Shutting down the web servr simulates an application being unreachable:
valet stop Valet services have been stopped. # from the healthcheck.log Healthcheck failed with an exception cURL error 7: Failed to connect to cli-demo.dev port 80: Connection refused (see http://ift.tt/1mgwZgQ)
Next, let’s bring our server back and remove the route so we can simulate an invalid status code.
valet start Valet services have been started.
Next, comment out the route in routes/web.php:
// Route::get('/', function () { // return view('welcome'); // });
If you aren’t running the scheduler, start it back up, and you should see an error message when the scheduler tries to check the status code:
Healthcheck failed for http://cli-demo.dev with a status of '404' (expected '200')
Don’t forget to shut down the infinite scheduler tab with Ctrl + C!
Further Reading
Our command simply outputs the result of the healthcheck, but you could expand upon it by broadcasting a failure to Slack or logging it to the database. On your own, try to set up some notification when the healthcheck fails. Perhaps you can even provide logic that it will only alert if three subsequent fails happen. Get creative!
We covered the basics of running your custom command, but the documentation has additional information we didn’t cover. You can easily do things like prompt users with questions, render tables, and a progress bar, to name a few.
I also recommend that you experiment with the Symfony console component directly. It’s easy to set up your own CLI project with minimal composer dependencies. The documentation provides knowledge that will also apply to your artisan commands, for example, when you need to customize things like hiding a command from command list.
Conclusion
When you need to provide your custom console commands, Laravel’s artisan command provides nice features that make it a breeze to write your own CLI. You have access to the service container and can create command-line versions of your existing services. I’ve built CLI tools for things like helping me debug 3rd party APIs, provide formatted details about a record in the database, and perform cache busting on a CDN.
via Laravel News http://ift.tt/2viI5d2
0 notes
mbaljeetsingh · 8 years ago
Text
Laravel Valet Supports Custom Per-Site Drivers
Laravel Valet is an incredible tool for getting a local development environment running in no time at all.
It’s driver based, and each driver adds support for a different type of application, framework, CMS, etc.
If you’d like to add support for something that doesn’t yet exist, it’s pretty simple to create your own driver, and share it with the community.
While there are a number different drivers out of the box, and even more that exist out there, some of them can make assumptions about how your project will be set up.
For example, the Laravel driver assumes your web root is located in a public directory. If you’ve renamed it to public_html, Valet simply won’t recognize that it’s Laravel.
To remedy this, you can create your own local driver that applies for a single project.
Just follow the steps to create a driver, but name it LocalValetDriver.php and place it in your project’s root directory.
<?php class LocalValetDriver extends LaravelValetDriver { public function serves() { return true; } public function frontControllerPath($sitePath, $siteName, $uri) { return $sitePath.'/public_html/index.php'; } }
You can either extend the base ValetDriver class to write the full driver from scratch or extend an existing driver and just override what you need.
via Laravel News http://ift.tt/2pkTl4O
0 notes