Quantcast
Channel: Laravel News
Viewing all 1734 articles
Browse latest View live

Laravel Certification Program Announced at Laracon 2017

$
0
0

A licensed Laravel certification platform was announced at Laracon EU this week, and a new landing page is up at laravel.com/certification/. The Laravel Certification is a Human Music B.V. product and is officially licensed by Laravel LLC.

The certification price will be €249 (about $295.78) for a personal certification and a team certification is €1245 (about $1478.90). Right now you can get a pre-order discount of €50 off on the personal certification and 15% on the team certification.

Here are the topics that will be covered in the certification test:

  • To pass the exam, you need to be fluent in building apps using the Laravel framework v5.5.
  • If your day job involves building Laravel applications, you’ll probably do fine. The exam is designed for you. That said, it’s probably a good idea to go over the Laravel documentation, and get a refresher.
  • If you’ve never built a Laravel application before, read the Laravel documentation, and try building some small to experiment with the various features.
  • Topics covered include (but not limited to): HTTP, routing, blade templating, services, localization, security, collections, queues, database, Eloquent, …
  • We’re also testing your knowledge of widely accepted best practices in the Laravel community.
  • You need working knowledge of recent PHP versions, including topics such as object oriented, closures, and various commonly used features.

The official site also provides a FAQ where you can read answers to the most frequently asked questions and submit a ticket to ask questions.

The certification has a board of advisors that “ensures high-quality exams, and guarantees that we can make the Laravel Certification program work to continually benefit the community.”

The board of advisors listed include Taylor Otwell, Freek Van der Herten, Chris Keithlin, Joe P Ferguson, and Duilio Palacios.

If you want to learn more, visit the certification page and follow along on Twitter @LaravelCert.


BotMan 2.0 PHP Chatbot Framework

$
0
0

BotMan is a framework agnostic PHP Chatbot framework designed to simplify the task of developing innovative bots for multiple messaging platforms, including Slack, Telegram, Microsoft Bot Framework, Nexmo, HipChat, Facebook Messenger, WeChat and many more.

BotMan 2.0 was released earlier this week with a bunch of improvements and exciting changes. From a project and code management perspective a couple of things happened:

  • BotMan and the various repositories around BotMan moved to the BotMan GitHub Organization instead of mpociot/botman.
  • Each Driver (Slack, Telegram, etc.) is contained in a separate repository outside of the BotMan core code
  • BotMan Studio bundles BotMan with the Laravel PHP Framework

Using the BotMan Chatbot Framework

On a basic level, a chat bot includes functionality to listen for messages, and respond to those messages. For example, if you ask your bot the weather, they might look up the weather from an API and then give you back the forecast.

Another way you can use BotMan is to listen for events. For example, you could greet a user when they join a channel or leave one.

From the Documentation, here’s how you can use BotMan from a web-accessible route in your application:

<?php

use BotMan\BotMan\BotMan;
use BotMan\BotMan\BotManFactory;

$config = [
    // Your driver-specific configuration
];

// create an instance
$botman = BotManFactory::create($config);

// give the bot something to listen for.
$botman->hears('hello', function (BotMan $bot) {
    $bot->reply('Hello yourself.');
});

// start listening
$botman->listen();

The above code is framework-agnostic, but the fluent API makes it simple to write a chatbot.

Advanced Topics

BotMan also supports advanced features, such as a middleware system, natural language processing (NLP), retrieving user information, and storage.

The middleware system has been expanded more in the 2.0 release, which allows you to hook into different parts of the ChatBot lifecycle. You could do powerful things like keep track of stats related to answered chats, and provide NLP on incoming messages. The available entry points for middleware are: sending, received, and heard.

Using the middleware, BotMan provides built-in support for the api.ai NLP service. Middleware makes your bots smarter and able to process more than just static text. A good example where this feature could be useful is the /remind feature, where you can use natural language to be reminded of something at a later time and date.

BotMan Studio

BotMan Studio—a packaged BotMan and Laravel application—provides testing tools, an out of the box web driver implementation, and additional tools like easier driver installation and configuration support.

BotMan studio can speed up development by providing a web driver implementation, which allows you to develop your chatbot locally and interact with it through a simple Vue.js chat widget, which lets you communicate with your bot without deploying it.

You can install drivers more easily with the artisan commands provided by BotMan studio:

# List available drivers
$ php artisan botman:list-drivers

# Install facebook
$ php artisan botman:install-driver facebook

You can create new BotMan projects with the BotMan installer in a similar way that you create new Laravel projects:

$ botman new weatherbot

Testing in BotMan Studio

The testing helpers in BotMan studio are slick! Here’s a simple example of the helpers provided:

/* @test */
$this->bot
    ->receives('Hi')
    ->assertReply('Hello!');

If you’ve used Laravel, you are familiar with the lovely testing helpers provided that make testing easier. Here’s a more complex conversation test example:

$this->bot
    ->receives('Hi')
    ->assertReplies([
        'Hello!',
        'Nice to meet you. What is your name?',
    ])->receives('BotMan')
    ->assertReply('BotMan, that is a beautifule name :-)');

The concept of how to test a chat bot feel foreign to me, but I am impressed with how elegant and straightforward the testing helpers make testing a chat bot!

New Features in 2.0

From the project’s changelog, here’s the gist of what’s new in BotMan 2.0:

  • Added ability to originate inline conversations.
  • Moved each driver into their own repository.
  • Facebook – Added support to send file and audio attachments.
  • Telegram – Added support to send file, audio and location attachments.
  • Added Kik driver.
  • Added custom Attachment classes.
  • Added support to listen for message service events.
  • Changed the way middleware works in BotMan.
  • Added support for Slack interactive menu messages.
  • Added Facebook Referral driver.
  • Allow replying to an existing thread for Slack drivers (#327).
  • Added loadDriver method to BotMan.
  • Added ability to use BotMan with a local socket.

Learn More

I am getting excited to write my chat bot! You can learn more by checking out the BotMan documentation and following the botman/botman GitHub project. You can also follow @botman_io and the creator @marcelpociot on Twitter.

Laravel Shareable Models Package

$
0
0

The Laravel Shareable Models package allows you to generate shareable links from your Eloquent models. Think dynamic routes which only exist for models that have been shared.

The package author Kai Sassnowski described his use-case for the Shareable Models package as follows:

My initial use case was giving certain non-admin user access to a certain resource that is usually only accessible through the admin interface.

Instead of mucking around with special permissions I created this method to create a completely new link from the resource that I wanted to share, that I could then treat like any other route in my application. So a separate controller and separate views. In that route, you can then simply only expose the functionality that you want (make it read-only for example or only show certain fields).

This package reminds me of the “get shareable link” feature in Google Drive. You could use this package in a file sharing application to share a particular model to outside users, but also be selective about which files, and which information you expose.

You can also do things like setting a password and an expiration date on shareable links, which require the user to enter a secret password. The package also ships with a password view that you can customize.

A basic example of creating a shareable link looks like the following:

<?php

$article = Article::find(1);

$link = ShareableLink::buildFor($article)
    ->setActive()
    ->build();

When you call build() you create the shareable link in the database, which uses a Polymorphic relationship to associate an article with a shareable link.

A shareable route might look something like the following:

Route::get('shared/{shareable_link}', ['middleware' => 'shared', function (ShareableLink $link) {
    return $link->shareable;
});

The shareable property is the associated model, so in the routing example above it would return a JSON version of the model.

Here’s an example of what a URL might look like using this package:

$ curl http://localhost:8000/shared/4aQQLDa525h8NVPGxLZ4hqx0l46

{
  "id": 1,
  "title": "The Raven",
  "contents": "Once upon a midnight dreary, while I pondered, weak and weary...",
  "created_at": "2017-05-31 19:35:28",
  "updated_at": "2017-05-31 19:35:28"
}

To learn more about the Laravel Shareable Models package, check out the documentation and the GitHub repository.

Find Files that Need Refactoring with Churn PHP

$
0
0

Churn PHP is a Command Line Interface (CLI) tool that helps you discover PHP files that might need refactoring. At a high level, Churn examines files in the path you provide and:

  • Checks how many commits a file has.
  • Calculates the cyclomatic complexity.
  • Creates a score based on these two values.

According to GitHub readme, Churn looks for files that match the following criteria and reports them back in a tabular format with a complexity and score:

A file that changes a lot and has a high complexity might be a better candidate for refactoring than a file that doesn’t change a lot and has a low complexity.

churn-php only assists the developer to identify files for refactoring. It’s best to use the results in addition to your judgment to decide which files you may want to refactor.

The primary usage from the command line looks like this:

$ composer require bmitch/churn-php --dev

# Specify one path
$ vendor/bin/churn run path/to/files/

# Specify multiple paths
$ vendor/bin/churn run path/one/ path/two/

You can also provide configuration for Churn PHP with a churn.yml file. You can define files that should be ignored, a minimum score required to be considered, and how far back to go in the commit history when considering how often a file has changed:

# The maximum number of files to display in the results table.
# Default: 10
filesToShow: 10

# The minimum score a file need to display in the results table.
# Default: 0
minScoreToShow: 0

# The number of parallel jobs to use when processing files.
# Default 10:
parallelJobs: 10

# How far back in the git history to count the number of commits to a file
# Can be a human readable date like 'One week ago' or a date like '2017-07-12'
# Default '10 Years ago'
commitsSince: One year ago

# Files to ignore when processing. The full path to the file relative to the root of your project is required
# Default: All PHP files in the path provided to churn-php are processed.
filesToIgnore:
 - src/Commands/ChurnCommand.php
 - src/Results/ResultsParser.php

There are a couple of caveats for running this package: it’s PHP 7+ only, and it currently doesn’t run on the Windows command line.

I ran Churn PHP on a couple of my codebases, and the results were enlightening on which files I should consider for refactoring. After getting back the results, they made sense to me and I could see how a few files should be refactored based on the results. Try it out on your own codebases, I think you’ll like it!

Learn more and get complete instructions on the GitHub repository.

Lumen 5.5 Is Released

$
0
0

Lumen 5.5 is now released and available for all. This is considered a maintenance release that upgrades the underlying packages to the Laravel 5.5 series.

Before upgrading your application to Lumen 5.5, you should review the Laravel 5.5 upgrade guide and make any applicable changes to your application according to which Laravel components you are using.

Once you have made the necessary adjustments to your application, you may upgrade your Lumen framework dependency in your composer.json file and run the composer update command:

"laravel/lumen-framework": "5.5.*"

For more information check out the official Lumen documentation.

Clean Code Concepts Adapted for PHP

$
0
0

Clean Code PHP (jupeter/clean-code-php), is a guide based on the book Clean Code: A Handbook of Agile Software Craftmanship, a classic programming book about writing maintainable code by Uncle Bob Martin.

The clean-code-php guide is inspired by a JavaScript adaptation, clean-code-javascript with PHP-specific features.

Here are a few of my favorite adaptations from the clean-code-php repository:

Don’t add unneeded context

Bad

<?php

class Car
{
    public $carMake;
    public $carModel;
    public $carColor;

    //...
}

Good

<?php

class Car
{
    public $make;
    public $model;
    public $color;

    //...
}

View Don’t add unneeded context in the guide.

Function Arguments (2 or fewer ideally)

Bad

<?php

function createMenu($title, $body, $buttonText, $cancellable) {
    // ...
}

Good

<?php

class MenuConfig
{
    public $title;
    public $body;
    public $buttonText;
    public $cancellable = false;
}

$config = new MenuConfig();
$config->title = 'Foo';
$config->body = 'Bar';
$config->buttonText = 'Baz';
$config->cancellable = true;

function createMenu(MenuConfig $config) {
    // ...
}

View Function Arguments in the guide.

Functions Should Do One Thing

Bad

<?php

function emailClients($clients) {
    foreach ($clients as $client) {
        $clientRecord = $db->find($client);
        if ($clientRecord->isActive()) {
            email($client);
        }
    }
}

Good

function emailClients($clients) {
    $activeClients = activeClients($clients);
    array_walk($activeClients, 'email');
}

function activeClients($clients) {
    return array_filter($clients, 'isClientActive');
}

function isClientActive($client) {
    $clientRecord = $db->find($client);
    return $clientRecord->isActive();
}

View View Functions Should Do One Thing in the guide.

Opinions, Opinions, Opinions

The author outlines the following about the purpose of the guide:

Not every principle herein has to be strictly followed, and even fewer will be universally agreed upon. These are guidelines and nothing more, but they are ones codified over many years of collective experience by the authors of Clean Code.

In a dynamic language like PHP (or any language for that matter), developers will disagree with some (or many) of the points made about the concepts demonstrated. I think the point I’d make is not to write off all ideas contained in the guide if you disagree with one or more ideas.

Learn More about Clean Code

I highly recommend that you read the Clean Code book to get a deeper understanding of the guidelines demonstrated in the PHP adaptation. On its own, the PHP guide is a good read, but part of the journey is learning how to spot code that needs some work and then adapting it.

Another great book related to Clean Code, is The Clean Coder: A Code of Conduct for Professional Programmers which focuses on you, the coder. In my opinion, these two books should be a must-read for programmers of any experience level looking to improve their code craftsmanship.

The Laravel Podcast Season Three

$
0
0

The official Laravel Podcast started back in 2013, and so far it’s been through two “seasons.” The first ran from 2013 through February 2015, with a mixture of guests and topics. Then came season two, which started in March of 2015 with Matt Stauffer as the host and it introduced Taylor Otwell and Jeffrey Way as regular guests/co-hosts.

Today Matt has announced that the podcast is transitioning into its third season of life. I had the opportunity to sit down with Matt to find out what we can expect with this new season.

Matt, welcome back to Laravel News and thanks for giving us the scoop on the next season. What can we expect this year?

The biggest change is that the format is moving from a cast of regulars (the vast majority of season two was Taylor, Jeffrey, and me) to an interview show. I’ll be bringing on a mixture of people who you’ve heard speak all the time–Taylor, Jeffrey, Adam, and I’m going to get other folks like you and Fideloper and folks on the conference circuit–and people you never get to hear from who are doing great work in the Laravel community.

The other thing is, though, I don’t want to ask the same questions. Especially since I’ll be interviewing some folks who’ve never been on a podcast before, I want to focus more on the people and less on the code.

Are you moving to the interview show because everyone is so busy? It must be hard to get everyone available to record at the same time.

You know, since season two was just Taylor, Jeffrey, and me, we all run our own businesses, so it really wasn’t that difficult. It’s more a natural thing that happened over time. We just got to a point where we didn’t have an incredible amount to talk about, and at times it could feel like a burden to put out another episode.

It’s like a good TV show, right? Do they keep the show going once the magic is gone? Or do they let it stop, or at least pause, when it’s time? That’s not saying the gang isn’t going to do a reunion tour in season four, but for now it’s a really helpful and healthy bit of breathing room for us.

I’m personally most excited to see you bring those people that are maybe not big names but have interesting stories. Are you planning on bringing on people from all over the world?

Exactly! We so commonly focus on folks from the US and Western Europe, and occasionally Canada and Australia. But what about the incredible thriving communities in Nigeria? Argentina? Brazil? Eastern Europe? What about the Spanish speaking communities? Or what about the amazing local meetups that we never hear about?

I’m also excited to put a story behind some of the names we’re familiar with because they’re so active in creating packages, writing blog posts, or answering StackOverflow questions. There’s one guy who’s the Laravel king on StackOverflow. There are a few names we’re all so familiar with from our composer.json files. But who are those people? What are their stories? That’s part of what I hope to tell this season.

With season three how often are you planning on publishing new episodes?

I’m thinking monthly to start off. I’d love to do it more frequently, but the amount of research, scheduling, and editing that goes into an interview show is a lot higher than a friends-hanging-out-around-a-topic was.

Also, I’m now finding the interviewees, prepping the interview questions, scheduling the interview, running it, and editing it, so there’s a lot more on my plate than there was with season two. I hope to be able to offload a bit of that over time, but for now, I want to set expectations realistically.

Are you thinking of running it for a certain number of months? Like a TV series season?

Oh. Man. That question has made me realize that I’m eventually going to have to make it more frequently than once a month: I have over 60 people in a Trello list who I’m ready to interview today, and that list is only growing.

When’s the new season start? And how do we listen to it?

I’ve scheduled a “preview” episode to go out on the podcast feed the same day this article goes out, so current subscribers should just get it in their podcatcher of choice. Not subscribed? Check it out now: http://laravelpodcast.com/

I think the first episode–the interview with Taylor–will go live in one week. That’s my goal. It’s recorded, so “all” I have left is to edit. Yes. One week. I’m gonna say that.

Facebook Releases Yarn Version 1.0

$
0
0

The Yarn package manager from Facebook just turned 1.0 today 11 months after its initial release. The new version touts some pretty impressive features that will make your life as a developer easier when you work with Node.js packages.

What’s New in Yarn 1.0?

On a high-level, Yarn 1.0 introduces the following big features:

  • Yarn Workspaces
  • Auto-Merging of lockfiles
  • Selective version resolutions

The workspaces feature was hard for me to grasp. I recommend you read more about workspaces in detail to understand it better.

This version includes many other improvements from the Yarn community. The community support and growth around Yarn has been significant in the short time it has been around. Yarn touts an active open-source community, with over 175,000 projects on GitHub.com using a yarn.lock file and now nearly 3 billion package downloads per month.

What is Yarn?

If you are not familiar with Yarn, it’s an alternative to NPM and uses a deterministic algorithm for installs using a lockfile. It’s touted to be faster and more secure than NPM. Once you install a package, Yarn caches it on your machine and uses the local version on subsequent installations. Installation is also very reliable, which can be a challenge when working with NPM.

Notable CI environments now have Yarn available by default and large companies like Twitter and Microsoft are seeing noticeable improvements in their process as a result of using Yarn.

If you want more details on the background of Yarn and why it exists, the introduction post from last year is a good place to learn more.

What about NPM?

Earlier this year, the NPM team released NPM 5.0. Version 5 introduces a few notable features, like the concept of a lock file (package-lock.json) and auto-install without using --save. NPM 5 also has significant performance improvements over previous releases. NPM improvements are exciting news for the Node.js community, and I hope that these two package managers push each other towards making improved package management tools for Node.js.

Even if you’re excited about NPM 5, I still personally think you’ll notice increased reliability and performance when you build and deploy with Yarn. I know I have. Developers transitioning to Yarn can still keep using NPM alongside Yarn. You can evaluate both and back out if you decide Yarn is not for you (but I bet you’ll love it).

Learn More

Read all about the official announcement of Yarn 1.0 and check out the official site for documentation and installation instructions.


Laravel 5.5.3 Released

$
0
0

Laravel 5.5.3, was released on September 8th and includes some nice additions and bugfixes. Let’s look at a few highlights, along with the full changelog of what’s new in 5.5.3.

The rescue() Helper

The rescue helper offers a clean way to return a default value on a Throwable exception. From the tests provided in #21010, here’s an example of how it works:

$result = rescue(function () {
    throw new Exception;
}, function () {
    return 'rescued!';
});

// => rescued!

A Route::getAction() parameter

Before Laravel 5.5.3, getting a key from the Route::getAction() method looks like this:

$route->getAction()['controller'];

In 5.5.3 you can now pass a parameter:

$route->getAction('controller');

The JSON Blade Directive

The @json directive can be used to inject PHP data into your templates as JSON.

Previously, you might do something like the following:

<script>
  var example = {!! $json !!};
</script>

I don’t like the syntax highlighting inconsistencies that sometimes ruin your editor syntax theme, or produces a JavaScript syntax error in your IDE like the above example.

To avoid the weird editor/IDE situation, I typically do the following to produce my JSON from a server-side response using addslashes(json_encode($json)) on the server:

<script>
  var example = JSON.parse("{!! $json !!}");
</script>

With the new Blade @json directive you can do something like the following:

<script>
  var example = @json($myData);
</script>

The @json directive is a good option that should provide you more convenience around using JSON in your template.

v5.5.3 Changelog:

Added

  • Added $action parameter to Route::getAction() for simpler access (#20975)
  • Added @json blade directive (#21004)
  • Added rescue() helper (#21010)
  • Support commas in In and NotIn parameters (#21012)
  • Added RedisManager::connections() method (#21014)
  • Added exception class to JSON exceptions (#21043)
  • Added Gate::policies() method (#21036)
  • Added geo spatial blueprint methods (#21056)

Changed

  • Fixed migrations not being run in batch order (#20986)
  • Flush application resources on teardown (#21022)
  • Catch errors while building exception context (#21047)
  • Return $this from Validator::setCustomMessages() (#21046)

Fixed

  • Make Request::validate() return the value of parent key (#20974)
  • Fixed date comparison validators failing when a format is specified (#20940)
  • Fixed login throttling failing when decayMinutes is more than 1 (#20997)
  • Only use reflection on classes in Kernel::load() (#20998)
  • Specify lower case column_name in MySqlGrammar::compileColumnListing() (#21037)
  • Fixed eager loading problem with BelongsToMany (#21044)

Removed

  • Remove unnecessary lcfirst() call in authorizeResource() (#21017)
  • Removed $listensFor from listener stubs (#21039)

The post Laravel 5.5.3 Released appeared first on Laravel News.

Laravel News T-Shirts – 2017 Edition

$
0
0

This years Laravel News t-shirt and hoodies are now available for purchase from Cotton Bureau.

It comes in two colors Charcoal and Heather, and come in three styles: a men’s tee, women’s tee, and a unisex hoodie that is perfect for those late night coding sessions.

These will only be available for purchase until Sep 25, 2017 at 8:00 PM EDT, show your support of Laravel News and reserve yours before time runs out.

The post Laravel News T-Shirts – 2017 Edition appeared first on Laravel News.

Getting to Know the Laravel Tinker Shell

$
0
0

Laravel includes a powerful REPL, called Tinker, powered by the PsySH console by Justin Hileman under the hood. The tinker console allows you to interact with your Laravel application from the command line in an interactive shell.

Tinker used to be part of the laravel/framework package, but with the release of Laravel 5.4 is extracted into separate package.

What is a REPL?

REPL stands for Read—Eval—Print—Loop, which is a type of interactive shell that takes in single user inputs, evaluates them, and returns the result to the user. I first learned about the concept of an interactive console through the rails console, which is part of the Ruby on Rails framework. Other languages, such as Ruby, come equipped with a REPL as a language feature. An interactive shell is a nice way to experiment with a language and framework.

PHP has an interactive shell you can use by running php -a (pointed out by @lcjury, but PsySH has more features so I use it for a general interactive shell for PHP and tinker for Laravel applications.

Using PsySH Outside of Laravel

I highly recommend that you install the psysh package globally. You can install the psysh command with composer by running the following:

composer global require psy/psysh:@stable

Make sure that your global composer bin/ is in your path so you can run psysh from anywhere:

export PATH="~/.composer/vendor/bin:$PATH"

To start an interactive session, run the psysh command. The following is an example of the built-in show command which can show you the source code of a command:

$ psysh
Psy Shell v0.8.11 (PHP 7.1.5 — cli) by Justin Hileman
>>> show array_key_exists
function array_key_exists($key, $search)
Source code unavailable.

The help command is your friend so that you can see the capabilities built-in to PsySH:

>>> help
  help
  ls
  dump
  doc
  show
  ...

I’ve removed the help command descriptions, but you get the idea.

You can even download the PHP core documentation as a CLI companion when you need to reference how a function works:

$ mkdir -p ~/.local/share/psysh/
$ wget -O \
  ~/.local/share/psysh/php_manual.sqlite
  http://psysh.org/manual/en/php_manual.sqlite

With the PHP Manual installed, you can read the documentation and then try it out in the CLI:

$ psysh
Psy Shell v0.8.11 (PHP 7.1.5 — cli) by Justin Hileman
>>> doc array_key_exists
psysh
Psy Shell v0.8.11 (PHP 7.1.5 — cli) by Justin Hileman
>>> doc array_key_exists
function array_key_exists($key, $search)

Description:
  Checks if the given key or index exists in the array

  array_key_exists() returns TRUE if the given $key
  is set in the array. $key can be any value
  possible for an array index.
...

>>> array_key_exists('car', ['bike' => 'BMX']);
=> false

I use PsySH all the time to verify how built-in PHP functions work and play around with PHP in an interactive way. Instead of using a REPL, I used to create an index.php file and run it with the PHP command to verify language features. Next time you do this, try using PsySH instead! The history command alone is worth using a REPL so you can recall previous commands.

Laravel Tinker: PsySH on Steroids

Like I mentioned earlier, the “tinker” command sits on top of vanilla PsySH. Think of tinker as one of the best ways to experiment with your Laravel application. Let’s look at a few nice features that should supercharge your development workflow with Laravel.

Documentation Commands

The doc command is a powerful way to look up documentation about a function or method. For example, let’s say you want to look up how the request() helper function works:

$ php artisan tinker
>>> doc request
function request($key = null, $default = null)

Description:
  Get an instance of the current request or an input item from the request.

Param:
  array|string  $key
  mixed         $default

Return:
  \Illuminate\Http\Request|string|array

Or maybe I want to see the request() code:

>>> show request
  > 633|     function request($key = null, $default = null)
    634|     {
    635|         if (is_null($key)) {
    636|             return app('request');
    637|         }
    638|
    639|         if (is_array($key)) {
    640|             return app('request')->only($key);
    641|         }
    642|
    643|         return data_get(app('request')->all(), $key, $default);
    644|     }

Artisan Commands in the Tinker Shell

When you run php artisan tinker, the command starts up an interactive PsySH shell with Laravel bootstrapped. Before running the shell, the tinker command adds commands to the shell. These commands get defined in the $commandWhitelist property of the TinkerCommand class.

protected $commandWhitelist = [
    'clear-compiled',
    'down',
    'env',
    'inspire',
    'migrate',
    'optimize',
    'up',
];

From this list, you can see that it’s possible to run up and down to toggle maintenance mode. You can also run migrate to perform any pending migrations. Last, you can run clear-compiled to clear the compiled class file.

Testing Laravel Code

Probably one of the most useful parts of Tinker, is the ability to play with Laravel code, such as models and services. You can use the console to create a new model for example:

$ php artisan tinker
>>> use App\User;
>>> $user = new User([
'name' => 'John',
'email' => 'john@example.com'
]);
$user->password = bcrypt('example');
=> "$2y$10$2l1vIXYJy.Q5otmdaaNG5./l4jbxpYYlhrSipZAsJRwAuuzjsSXlq"
$user->save();
=> true
$user->toArray();
=> [
     "name" => "John",
     "email" => "john@example.com",
     "updated_at" => "2017-09-12 06:37:13",
     "created_at" => "2017-09-12 06:37:13",
     "id" => 1,
   ]

Here’s my favorite database-related command in a Tinker session, the humble factory() helper to create test users:

$ php artisan tinker
>>> use App\User;
>>> factory(User::class, 5)->create();
...

Here’s how you could query the User model to get ten results back from the users table:

$php artisan tinker
>>> use App\User;
>>> User::limit(10)->get();
=> Illuminate\Database\Eloquent\Collection {#1071
     all: [
       App\User {#1072
         id: 1,
         publisher_id: null,
         name: "John",
         email: "john@example.com",
         created_at: "2017-09-12 06:37:13",
         updated_at: "2017-09-12 06:37:13",
       },
        ],
    }
>>>

Tinker is a good place to trigger manual jobs and experiment with things like services, jobs, and events. For example, here we’re getting the log service from the container and writing to the log:

$ php artisan tinker
>>> $log = app('log');
=> Illuminate\Log\Writer {#1042}
>>> $log->info('test');
=> null

Learn More

The best way to find out more is to dive into a tinker session and use the help command if you forget the commands you can run. The official psysh documentation is an excellent resource to get familiar with the underlying interactive shell. The interactive debugger capabilities and the wtf command are some features you should check out. If you want to learn more about how tinker works, see the laravel/tinker package on GitHub.

Edit 09/12/2017: @lcjury pointed out that PHP does include an interactive shell by running php -a from the command line.

The post Getting to Know the Laravel Tinker Shell appeared first on Laravel News.

Sublime Text 3.0 is released

$
0
0

Sublime Text 3.0 is now released and it features a refreshed UI theme, new color schemes, and a new icon. Everything has been improved since v2 and includes better performance.

From their release announcement:

Certainly there are big features that 3.0 has: Goto Definition, a new syntax highlighting engine, a new UI, and an expanded API. However the difference is frequently felt in the hundreds of improvements that don’t warrant being featured on their own: spell checking works better, automatic indentation does the right thing more often, word wrapping handles source code better, high DPI screens are properly supported, and Goto Anything is smarter. There’s too much to list, but combined the difference is night and day.

One of the areas I’m especially proud of in Sublime Text 3 is performance: it’s significantly faster than Sublime Text 2 along every axis. Startup is faster, opening files is faster, and scrolling is more efficient. While it’s a much larger application than 2, it feels leaner.

If you’ve purchased a license after 2013 your license is valid for v3 and upgrades are available if you purchased before 2013.

The post Sublime Text 3.0 is released appeared first on Laravel News.

Dynamic templates in Laravel Blade with View::first

$
0
0

When building dynamic components or pages sometimes we want to display a custom template if it exists or otherwise fall back on a default one.

For example, imagine we are building a pages module, and some pages like “About Us” or “Contact Us” will need a custom template (for example to display pictures or a contact form), while others like “Terms of services” will do fine with a default template.

We can solve this problem with a series of conditionals or by using view()->exists() to check if a custom template exists or not, however, Laravel 5.5 brings us a better and more elegant way as I’ll demonstrate in the following video:

Using View::first

The view()->first() method allows us to replace the following code:

if (view()->exists('custom-template')) {
    return view('custom-template', $data);
}

return view('default-template', $data);

With a simpler, more expressive version:

return view()->first(
    ['custom-template', 'default-template'], $data
);

You have to pass an array of templates as the first argument and the first method will load the first template it finds.

Of course, you can pass as many templates as you want and even use dynamic names:

return view()->first([
    "pages/{$page->slug}",
    "pages/category-{$page->category->slug}",
    "pages/default-template"
], $data);

Remember you can also use this feature using its facade version:

\View::first($templates, $data)

This dynamic view loading feature was added to Blade in Laravel v5.5 and is a great way of keeping your controllers simple by avoiding extra conditionals when dealing with dynamic templates.

The post Dynamic templates in Laravel Blade with View::first appeared first on Laravel News.

Laravel 5.5 Now Includes TrustedProxy

$
0
0

Laravel v5.5 was released just a week ago at Laracon EU. You may have noticed that the v5.5 composer.json file requires the fideloper/proxy composer package. For me, this is one of those packages I must include immediately on every project because I use Amazon Web Services and Google Cloud every day, so I am thankful Laravel 5.5 includes this package by default.

Setting up the package is a breeze, and I especially appreciate that this package takes care of redundant setup. Let’s briefly cover what this package provides for Laravel, and why it’s an important package in the Laravel ecosystem.

What Does the TrustedProxy Package Do?

On a high level, Trusted Proxy tells Laravel about proxies that can be trusted and how to map X-Forwarded-* headers from the request.

The package readme probably does a better job summarizing:

Setting a trusted proxy allows for correct URL generation, redirecting, session handling and logging in Laravel when behind a proxy.

This is useful if your web servers sit behind a load balancer, HTTP cache, or other intermediary (reverse) proxy.

Laravel uses Symfony for handling Requests and Responses. These classes have the means to handle proxies. However, for security reasons, they must be informed of which proxies to “trust” before they will attempt to read the X-Forwarded-* headers.

Laravel does not have a simple configuration option for “trusting” proxies out of the box. This package simply provides one.

Working with Proxies

It’s commonplace for developers to need to work with cloud providers like Amazon Web Services and Content Delivery Networks (CDN) like Cloudflare for full site delivery, with the application sitting behind these services instead of being exposed directly to the world. Also, your application might even be behind a chain of proxies.

When your website or application has DNS pointed at CloudFlare, for example, the HTTP requests get proxied from CloudFlare to your application.

For example, ou might notice a few CloudFlare headers in the HTTP responses on Laravel News:

$ curl -I https://laravel-news.com/laravel-5-5
HTTP/1.1 200 OK
Date: Wed, 13 Sep 2017 04:15:50 GMT
Content-Type: text/html; charset=UTF-8
Connection: keep-alive
Cache-Control: no-cache
Server: cloudflare-nginx
CF-RAY: 39d849a3df7a39e2-PHX

You can see a couple headers (CF-RAY and Server for example) being sent back in the cURL response. CloudFlare is proxying the request to the actual application, getting the response, appending a few headers, and sending the response back to the end-user.

Since CloudFlare is proxying between the end user and the application, all requests look the same to the application. To let the application know important details about the originating request, proxies send along X-Forwarded* headers.

Here are a few common headers that proxies will send along:

  • X-Forwarded-For – a standard header for defining the originating IP address (reference)
  • X-Forwarded-Host – a de-facto standard header for identifying the protocol, such as HTTP or HTTPS (reference)
  • X-Forwarded-Proto – a de-facto standard header for identifying the protocol, such as HTTP or HTTPS (reference)
  • X-Forwarded-Port – helps you identify the port that the client used to connect to the load balancer (reference)

Not all proxies use the de-facto standard headers, but this package can help you map those headers so that the underlying Symfony request object knows how to trust the proxy and get the correct values.

HTTPS -> HTTP

If you terminate TLS/SSL at the load-balancer level, your application might receive requests internally on HTTP, but actually the originating request from users is HTTPS. If you are in this situation, your application will receive header like this (among others) from the proxy:

X-Forwarded-Proto: https

The TrustProxies middleware automatically makes the Request object aware of the proxy headers by calling Symfony’s HttpFoundation Request::setTrustedProxies() method, and thus any PHP-generated URIs will know to use HTTPS, even though the request was made via HTTP. Without calling setTrustedProxies(), a Laravel application wouldn’t know about the originating request and how to properly deal with that request.

Configuration

The fideloper/proxy package provides the following Laravel configuration so you can adapt the package to work in a variety of settings, including providing mapping if your proxies use non-standard header names:

<?php

return [

    /*
     * Set trusted proxy IP addresses.
     *
     * Both IPv4 and IPv6 addresses are
     * supported, along with CIDR notation.
     *
     * The "*" character is syntactic sugar
     * within TrustedProxy to trust any proxy
     * that connects directly to your server,
     * a requirement when you cannot know the address
     * of your proxy (e.g. if using Rackspace balancers).
     *
     * The "**" character is syntactic sugar within
     * TrustedProxy to trust not just any proxy that
     * connects directly to your server, but also
     * proxies that connect to those proxies, and all
     * the way back until you reach the original source
     * IP. It will mean that $request->getClientIp()
     * always gets the originating client IP, no matter
     * how many proxies that client's request has
     * subsequently passed through.
     */
    'proxies' => [
        '192.168.1.10',
    ],

    /*
     * Or, to trust all proxies that connect
     * directly to your server, uncomment this:
     */
     # 'proxies' => '*',

    /*
     * Or, to trust ALL proxies, including those that
     * are in a chain of forwarding, uncomment this:
    */
    # 'proxies' => '**',

    /*
     * Default Header Names
     *
     * Change these if the proxy does
     * not send the default header names.
     *
     * Note that headers such as X-Forwarded-For
     * are transformed to HTTP_X_FORWARDED_FOR format.
     *
     * The following are Symfony defaults, found in
     * \Symfony\Component\HttpFoundation\Request::$trustedHeaders
     *
     * You may optionally set headers to 'null' here if you'd like
     * for them to be considered untrusted instead. Ex:
     *
     * Illuminate\Http\Request::HEADER_CLIENT_HOST  => null,
     *
     * WARNING: If you're using AWS Elastic Load Balancing or Heroku,
     * the FORWARDED and X_FORWARDED_HOST headers should be set to null
     * as they are currently unsupported there.
     */
    'headers' => [
        (defined('Illuminate\Http\Request::HEADER_FORWARDED') ? Illuminate\Http\Request::HEADER_FORWARDED : 'forwarded') => 'FORWARDED',
        Illuminate\Http\Request::HEADER_CLIENT_IP    => 'X_FORWARDED_FOR',
        Illuminate\Http\Request::HEADER_CLIENT_HOST  => 'X_FORWARDED_HOST',
        Illuminate\Http\Request::HEADER_CLIENT_PROTO => 'X_FORWARDED_PROTO',
        Illuminate\Http\Request::HEADER_CLIENT_PORT  => 'X_FORWARDED_PORT',
    ]
];

The configuration allows you to define the IP addresses you want to trust, or you can trust all direct proxies with * and any proxy in a chain of proxies with **. Please consult the documentation carefully, as well as the final part of this article to read about locking down your applications that are behind proxies.

You can create the config/trustedproxy.php configuration by running vendor:publish:

php artisan vendor:publish --provider="Fideloper\Proxy\TrustedProxyServiceProvider"

In Laravel 5.5, running vendor:publish without arguments will use an interactive mode which makes publishing the vendor file even easier.

Learn More

Symfony has a short write-up How to Configure Symfony to Work behind a Load Balancer or Reverse Proxy with some valuable information. Specifically, the following security considerations are crucial when working with proxies:

Some reverse proxies (like Amazon’s Elastic Load Balancers) don’t have a static IP address or even a range that you can target with the CIDR notation. In this case, you’ll need to – very carefully – trust all proxies.

  1. Configure your web server(s) to not respond to traffic from any clients other than your load balancers. For AWS, this can be done with security groups.
  2. Once you’ve guaranteed that traffic will only come from your trusted reverse proxies, configure Symfony to always trust incoming request.

Check out fideloper/proxy, which has an extensive readme on how to set up the TrustProxies middleware and configuration with a ton of information on the subject.

The post Laravel 5.5 Now Includes TrustedProxy appeared first on Laravel News.

Testing With PhpSpec

$
0
0

PhpSpec is a testing tool based on the concept of emergent design using specification. You may have heard of Behavior Driven Development (BDD), and PhpSpec is a tool to use at the spec level or SpecBDD. We also mentioned PhpSpec in our recent roundup of Laravel Testing Resources, which includes ways you can incorporate PhpSpec into your Laravel workflow if you are interested in trying out SpecBDD.

If you’ve never tried PhpSpec, one of the things that I love about PhpSpec is that the process generates code for you and guides you through the SpecBDD process through the command line. Let me show you what I mean with a quick tutorial.

Getting Started

If you want to follow along, make sure you have Composer installed and in your path. The first thing we’re going to do is create a new project. When I am tinkering with libraries, I like to create a project in a folder I call “Sandbox”:

$ mkdir -p ~/Code/sandbox/calculator-phpspec && cd $_
$ mkdir src/

$ composer init
$ composer require --dev phpspec/phpspec

Next, let’s add a PSR-4 namespace to our project’s composer.json file, in the end, your file will look similar to this:

{
    "name": "predmond/calculator-phpspec",
    "require": {},
    "require-dev": {
        "phpspec/phpspec": "^4.0"
    },
    "autoload": {
        "psr-4": {
            "Predmond\\Calculator\\": "src/"
        }
    }
}

Before we forget, let’s dump the autoloader so our namespace can be used later:

$ composer dump-autoload
Generating autoload files

You should be able to run the phpspec CLI now:

# I like to have /vendor/bin in my path
export PATH="./vendor/bin:$PATH"

# Or run it with the path
$ ./vendor/bin/phpspec
phpspec 4.0.3

Usage:
  command [options] [arguments]
...

Configuring Our Suite

PhpSpec will look for a configuration file in the root of the project for a phpspec.yml file. We can use this file to configure test suites, formatters, and other configuration rules.

The configuration documentation is pretty extensive, so you should check it out, but for our purposes, we just want to configure our PSR-4 namespace so I can walk you through the workflow of using PhpSpec to drive out a specification.

PhpSpec uses a top-level YAML key called “suites” so let’s define a default suite for our project’s namespace by creating a phpspec.yml file in the root of our project:

suites:
    default:
        namespace: Predmond\Calculator
        psr4_prefix: Predmond\Calculator
formatter.name: pretty

We can use this suite to create a calculator class and drive out a basic calculator spec. Let’s get to work!

The Workflow

Our workflow with PhpSpec will typically look like the following steps:

  1. Describe a Specification
  2. Run the Specification (Create the class if it doesn’t exist)
  3. Write an expected behavior
  4. Run the specification (create the method if it doesn’t exist)
  5. Write the implementation
  6. Verify the behavior
  7. Repeat

The way PhpSpec works does a good job of forcing you into this BDD workflow, which you might fight at first, but tends to be a reliable coding workflow once you get comfortable. Let’s go through a quick example of the workflow so you can give it a shot!

Describing a Spec

The first thing we need to do is define a specification. In our example, we are going to describe a calculator. You define a specification (think of it as creating a test class) by using the describe command. Run the following to create a Calculator spec:

$ ./vendor/bin/phpspec describe Predmond/Calculator/Calculator

# Or you can use backslashes with quotes
$ ./vendor/bin/phpspec describe "Predmond\Calculator\Calculator"

Running this command creates our specification file in spec/CalculatorSpec.php which looks like the following:

<?php

namespace spec\Predmond\Calculator;

use Predmond\Calculator\Calculator;
use PhpSpec\ObjectBehavior;
use Prophecy\Argument;

class CalculatorSpec extends ObjectBehavior
{
    function it_is_initializable()
    {
        $this->shouldHaveType(Calculator::class);
    }
}

Take note that we haven’t created the actual Calculator class yet. Our file includes one specification file (it_is_initializable)—PhpSpec uses it_ and its_ with public functions to find specifications.

Also, take note of the underscore method name convention, which is an opinionated style that tends to be more readable. One goal of BDD is using language friendly to humans to describe behavior.

Now that we have our specification, let’s use run to run our specs:

$ ./vendor/bin/phpspec run
      Predmond\Calculator\Calculator

  11  ! is initializable
        class Predmond\Calculator\Calculator does not exist.
...
1 specs
1 examples (1 broken)
18ms

Do you want me to create `Predmond\Calculator\Calculator` for you? [Y/n]

Enter “Y” and PhpSpec will create the Calculator class. Rerunning the specifications should make our it_is_initializable spec pass:

$ ./vendor/bin/phpspec run

      Predmond\Calculator\Calculator

  11  ✔ is initializable

1 specs
1 examples (1 passed)
9ms

You’ve just described your first specification, and PhpSpec took care of the details of creating methods and code for us! Let’s dig into creating more specifications.

Creating an Addition Specification

Let’s drive out a design for addition in our Calculator class. Our specifications are green, so we are ready to write a new specification before implementing it. Open up the `spec/CalculatorSpec.php file and add the following:

function it_can_add_two_numbers()
{

}

I didn’t add any code because I want to show you how PhpSpec guides you on what to do next, which is pretty neat:

$ ./vendor/bin/phpspec run

      Predmond\Calculator\Calculator

  11  ✔ is initializable
  16  - can add two numbers
        todo: write pending example

1 specs
2 examples (1 passed, 1 pending)
11ms

PhpSpec is telling us that we have a pending specification. Let’s drive it out now:

function it_can_add_two_numbers()
{
    $this->add(2,3)->shouldReturn(5);
}

We are using the specification to say: “call add() with the parameters 2, and 3, and add() should return 5.

Here’s an important point to understand: $this is the object we are describing. You don’t need to construct the object as you would in other test suites:

# Other test suites
$calculator = new Calculator();

# PhpSpec $this is the Calculator
$this->add(); // And string some matching expectations...

If we try to run our specification now, PhpSpec will tell us the next step:

$ ./vendor/bin/phpspec run

      Predmond\Calculator\Calculator

  11  ✔ is initializable
  16  ! can add two numbers
        method Predmond\Calculator\Calculator::add not found.

----  broken examples

        Predmond/Calculator/Calculator
  16  ! can add two numbers
        method Predmond\Calculator\Calculator::add not found.

1 specs
2 examples (1 passed, 1 broken)
11ms

  Do you want me to create
  `Predmond\Calculator\Calculator::add()` for you? [Y/n]
$ ./vendor/bin/phpspec run

      Predmond\Calculator\Calculator

  11  ✔ is initializable
  16  ✘ can add two numbers
        expected [integer:5], but got null.

----  failed examples

        Predmond/Calculator/Calculator
  16  ✘ can add two numbers
        expected [integer:5], but got null.

1 specs
2 examples (1 passed, 1 failed)
11ms

PhpSpec will define the add() method on our implementation if we confirm “Y”. Kind of cool, eh?

Once you confirm, immediately our specification fails. That means it’s time to write the minimal amount of code to get the specification to pass.

Our Calculator class has been generated by PhpSpec at this point. Here’s what it should look like:

<?php

namespace Predmond\Calculator;

class Calculator
{
    public function add($argument1, $argument2)
    {
        // TODO: write logic here
    }
}

Based on our it_can_add_two_numbers() specification, PhpSpec has created a public add() method with two arguments defined. Let’s do the minimal amount to get this test passing:

public function add($argument1, $argument2)
{
    return 5;
}

Most of the time doing this minimal amount of code is ridiculous but stick with me because when you test more complex specification writing the minimum amount of code can help you build a robust specification.

Now that we’ve written the minimal amount of code, it’s time to rerun our specs:

$ ./vendor/bin/phpspec run

      Predmond\Calculator\Calculator

  11  ✔ is initializable
  16  ✔ can add two numbers

1 specs
2 examples (2 passed)
20ms

We have a passing spec! It’s not very useful—but it’s green.

Let’s add a few more examples to our specification to drive the implementation:

function it_can_add_two_numbers()
{
    $this->add(2, 3)->shouldReturn(5);
    $this->add(10, 0)->shouldReturn(10);
    $this->add(0, 0)->shouldReturn(0);
    $this->add(1, -2)->shouldReturn(-1);
}

If you rerun your specs, our addition spec will fail in a blaze of glory. We are ready to update our implementation to get things back to green now:

public function add($argument1, $argument2)
{
    return $argument1 + $argument2;
}

Running phpspec should result in both specifications passing.

Division

Let’s quickly write a more interesting specification: preventing a division by zero error. When this happens, we will throw an exception.

The specification might look like this:

function it_can_divide_two_numbers()
{
    $this->divide(10, 2)->shouldReturn(5);
}

function it_throws_a_division_by_zero_excption()
{
    $this->shouldThrow('\Predmond\Calculator\DivisionByZeroException')->duringDivide(10, 0);
}

And the implementation:

public function divide($argument1, $argument2)
{
    return $argument1 / $argument2;
}

If you run the specs you should get a division by zero warning:

$ ./vendor/bin/phpspec run

      Predmond\Calculator\Calculator

  11  ✔ is initializable
  16  ✔ can add two numbers
  24  ✔ can divide two numbers
  29  ✘ throws a division by zero exception
        expected exception of class "\Predmond\Calculator\Divi...", but got
        [exc:PhpSpec\Exception\Example\ErrorException("warning: Division by zero in
        /Users/predmond/Code/sandbox/calculator-phpspec/src/Calculator.php line 14")].

Let’s fix that by throwing the exception when the denominator is zero:

public function divide($numerator, $denominator)
{
    if ($denominator === 0) {
        throw new DivisionByZeroException();
    }

    return $numerator / $denominator;
}

And make sure to create the exception class in the src/ folder:

<?php

namespace Predmond\Calculator;

class DivisionByZeroException extends \Exception {}

And running our specs should pass now:

$ ./vendor/bin/phpspec run

      Predmond\Calculator\Calculator

  11  ✔ is initializable
  16  ✔ can add two numbers
  24  ✔ can divide two numbers
  29  ✔ throws a division by zero exception

1 specs
4 examples (4 passed)
13ms

Constructing Objects and Matchers

There are two important concepts I want to introduce before we wrap up: constructing objects and matchers.

Our Calculator class is pretty basic, but you will likely need to construct objects that have dependencies. You should read the object construction section to get an overview.

Matchers are used in PhpSpec to describe how an object should behave. You’ve already used the identity matcher when you called $this->add(2, 3)->shouldReturn(5);. The shouldReturn uses the identity operator (===) to make sure the spec matches expectations. The four types of identity matchers you can use are:

$this->calculatorMemory()->shouldBe(5);
$this->getTitle()->shouldBeEqualTo("Star Wars");
$this->getReleaseDate()->shouldReturn(233366400);
$this->getDescription()->shouldEqual("Inexplicably popular children's film");

You’ve also used the Throw Matcher when we expected our divide() method to throw a DivisionByZeroException exception.

You can check out the full matchers documentation and use it as a reference to work with PhpSpec.

Learn More

We’ve just scratched the surface of what PhpSpec can do. We didn’t demonstrate collaborators, but perhaps we can do a follow-up post with more examples. You should read through the whole PhpSpec manual, which isn’t very long. Once you get a handle on things, learn about Prophet Objects which include stubs, mocks, and spies.

I have a small HTML to AMP library that uses PhpSpec (and uses TravisCI). Mike Stowe has an excellent introductory article called What is Spec Driven Development that will give you an overview of SpecBDD.

The post Testing With PhpSpec appeared first on Laravel News.


Creating Your Own Configuration in Laravel

$
0
0

Laravel configuration allows you to define per-environment configuration with the excellent vlucas/phpdotenv package.

If you are new to Laravel, you might not yet know how you can create your configuration files in your projects and a few other helpful things that will help you master configuration. As always, the official documentation provides great information, and there are a few things we’ll cover here that I think will help people new to the Laravel framework.

How Does Configuration Work?

At a high level, configuration files are located in the config/ folder of a Laravel project. The framework ships with various configuration files that make it easy for you to do things like pick which database driver you want to use and define external services.

For example, here is a partial view of the config/services.php config file:

return [
    // ...
    'mailgun' => [
        'domain' => env('MAILGUN_DOMAIN'),
        'secret' => env('MAILGUN_SECRET'),
    ],

        // ...

Note the env() calls that you can use to change values per-environment with the .env file or on the host system directly.

When you define an environment configuration on your machine, it takes precedence over the .env file.

The env() helper also allows you to specify a default value when the environment variable is missing on the system or the .env file. For example, the default connection in config/database.php is mysql when the DB_CONNECTION environment variable is not defined:

<?php

return [
    'default' => env('DB_CONNECTION', 'mysql'),

    // ...
];

All environment values from the phpdotenv package come back as strings, but the env() helper in Laravel does extra work with environment variables. For example, the Laravel helper converts “false” the string to Boolean false, the keyword “empty” to an empty string, and “null” to a null value. You can check out the source of the Illuminate support helpers.php file for more details.

Accessing the Configuration Service

The most common ways to access configuration in Laravel is through the Configuration service or the config() helper.

Here’s how you use the config service:

$ php artisan tinker

>>> app('config')->get('services');
=> [
     "mailgun" => [
       "domain" => null,
       "secret" => null,
     ],
     "ses" => [
       "key" => null,
       "secret" => null,
       "region" => "us-east-1",
     ],
     "sparkpost" => [
       "secret" => null,
     ],
     "stripe" => [
       "model" => "App\User",
       "key" => null,
       "secret" => null,
     ],
   ]

The config() helper provides convenience, and you can still access the configuration repository service if you don’t pass any arguments:

$ php artisan tinker

>>> config()
=> Illuminate\Config\Repository {#37}

>>> config()->get('services')
...
>>> config('services')

Working with Configuration

Configuration is defined in PHP arrays, and you can access those array values with a dot notation. The first part of the configuration key matches the name of the file. For example, the following is the config/services.php file:

$ php artisan tinker

>>> config('services.mailgun');
=> [
     "domain" => "mg.example.com",
     "secret" => "secret",
   ]
>>> config('services.mailgun.domain');
=> mg.example.com

Just like the env() helper, the config helper allows you to specify a default value if the configuration key isn’t defined:

$ php artisan tinker

>>> config('my.invalid.key', 'mg.example.com');
=> mg.example.com

You can also change/set configuration at runtime by passing the configuration helper an array:

>>> config(['example' => 'Hello World']);
=> null
>>> config('example');
=> "Hello World"

>>> config([
... 'view.paths' =>
... array_merge(config('view.paths'), ['my/other/path/'])
... ]);

Creating Your Own Configuration

You can create your own configuration files by adding them to the config/ folder:

$ touch config/api.php

You would then access the configuration values by prefixing “api”:

>>> config('api.base_url');

This is just an example, for services like APIs just use the config/services.php file by adding new keys, for example, let’s say you are adding auth0 to services.php:

<?php

return [
    'auth0' => [
        'secret' => env('AUTH0_CLIENT_SECRET')
    ],
];

Optimizing Configuration

When you deploy your application to production, you should optimize your configuration by running the following command:

$ php artisan config:cache

There are a couple of important points to make about this command:

  1. This command is not intended for development environments
  2. Make sure you are not calling env() outside of configuration files

When you cache configuration, things like tests will use these cached values. For example, your database credentials will be cached and running tests with database interactions will drop your database tables.

When you cache your configuration, make sure your code is not calling the env() helper. You should be using config() wherever you need to access configuration. The correct way to provide configuration to your application is using configuration files in tandem with environment variables with sensible default values.

You can clear the configuration cache with the following artisan command:

$ php artisan config:clear

Learn More

I hope this has been helpful to those just starting to learn about Laravel. Be sure to read the official configuration documentation. If you are interested in writing your packages, check out the package configuration resources documentation.

The post Creating Your Own Configuration in Laravel appeared first on Laravel News.

Take the Laravel 2017 Survey

$
0
0

Last year we partnered up with LaraJobs to put together a survey to see what types of projects people are taking on with Laravel as well as get some feedback on what the Laravel community could be doing better. The results ended up with over 1,600 submissions and some interesting insights.

Because of the popularity we are bringing it back again this year and if you’re a Laravel developer or in charge of a Laravel team and have a few minutes we’d love for you to take the survey.

The survey will remain open for a few weeks and then we will turn it off and share the results.

The post Take the Laravel 2017 Survey appeared first on Laravel News.

The Top Five Laravel Community Editor Themes

$
0
0

We’ve assembled the top editors and themes from hundreds of developers, and we’re happy to share the results with you. The editor theme is one of those bling items that you get to show off a bit. To find out what everyone is using for an editor and theme, we asked on Twitter and Facebook and had tons of responses.

Visit Laravel News for the full post.

The post The Top Five Laravel Community Editor Themes appeared first on Laravel News.

GitHub Desktop 1.0 is Now Available

$
0
0

GitHub announced today that GitHub Desktop 1.0 is now available on Mac and Windows. The new GitHub Desktop version has been revamped and redesigned with Electron and has some cool new features that will make you more productive in the app.

Visit Laravel News for the full post.

The post GitHub Desktop 1.0 is Now Available appeared first on Laravel News.

Laravel 5.5.5 Released With a New Route Fallback to Help Customize Your 404 Views

Viewing all 1734 articles
Browse latest View live