•    PHP 7.1 is now released - Featuring nullable types, class constants, and more. 

    Today, the PHP team has released 7.1.0 that includes new features such as Nullable types, Void return type, Class constant visibility modifiers, and more. Here is a quick overview of some of the new features.

    Nullable Types

    This adds a leading question mark indicate that a type can also be null.

    function answer(): ?int  {
        return null; //ok
    }
    
    function answer(): ?int  {
        return 42; // ok
    }
    
    function answer(): ?int {
        return new stdclass(); // error
    }
    

    Void Return Type

    This requires that a function not return any value:

    function should_return_nothing(): void {
        return 1; // Fatal error: A void function must not return a value
    }
    
    function lacks_return(): void {
        // valid
    }
    
    function returns_nothing(): void {
        return; // valid
    }
    
    function returns_null(): void {
        return null; // Fatal error: A void function must not return a value
    }
    

    Class constant Visibility

    You now have the ability to set the visibility on class constants.

    class Token {
        // Constants default to public
        const PUBLIC_CONST = 0;
    
            // Constants then also can have a defined visibility
            private const PRIVATE_CONST = 0;
            protected const PROTECTED_CONST = 0;
            public const PUBLIC_CONST_TWO = 0;
    
            //Constants can only have one visibility declaration list
            private const FOO = 1, BAR = 2;
    }
    

    For a full list of new features take a look at the release announcement and changelog.

  •    Auto Publishing to Telegram using Notification Channels 

    Laravel Notifications are great when you need to send notifications out through a variety of channels. Based on the documentation the original use case for these is to send quick information messages that notify users of something that occurred in your application. For example, if you are writing a billing application, you might send an “Invoice Paid” notification to your users via the email and SMS channels.

    However, they don’t have to be restricted just those types of notifications. For example, on this site every time a new post is published I want it to go out to all the various social channels and the community has created a lot of drivers for various services.

    One new area that I created a few months back, is a read-only Laravel News Telegram group, and in the past, I would manually add the day’s new posts into it. As you can imagine one day I forgot to do this, then the next, and so on. I knew I had to automate the sending of new posts and that is where the Telegram Notification package comes in, let’s take a look at how to get this setup and auto sending notifications to your Telegram room.

    Creating a Telegram Bot

    Before you can send messages to a room, you have to create a bot. To start, send a new message to @BotFather, and it goes like this:

    You: /newbot
    BotFather: Alright, a new bot. How are we going to call it? Please choose a name for your bot.
    
    You: MyTestBot
    BotFather: Good. Now let's choose a username for your bot. It must end in bot. Like this, for example: TetrisBot or tetris_bot.
    
    You: MyNewBot
    BotFather: Done! Congratulations on your new bot. ... Use this token: xxxxxx 
    

    Now you will need that token later to add to your .env file so just keep it handy for now.

    Add the bot to your room

    Open your Telegram room and go to the settings -> administrators and add the bot you just created to the channel. This gives it access to post new messages to the room.

    Install Telegram Notifications

    Installation is typical for any Laravel package. First require the package:

    composer require laravel-notification-channels/telegram
    

    Add it to the providers in app.php:

    'providers' => [
        ...
        NotificationChannels\Telegram\TelegramServiceProvider::class,
    ],
    

    Add the config array:

    // config/services.php
    ...
    'telegram-bot-api' => [
        'token' => env('TELEGRAM_BOT_TOKEN', 'YOUR BOT TOKEN HERE')
    ],
    

    Finally, open .env and add your token:

    TELEGRAM_BOT_TOKEN=1234:232jkl42l4j23kl
    

    Create a new notification class

    For my use case I am going to send a notification when a new post is published so I create a new PostPublished notification class through artisan:

    php artisan make:notification PostPublished
    

    Now open the file and adjust the via method to tell it to use the TelegramChannel:

    public function via($notifiable)
    {
        return [TelegramChannel::class];
    }
    

    Next, create a toTelegram method that will contain the details you want sent:

    public function toTelegram($post)
    {
        return TelegramMessage::create()
            ->to('@laravelnews')
            ->content($post->title.' https://laravel-news.com/'. $post->uri);
    }
    

    In this case, it’s sending to the @laravelnews room with the content of the post title and a link to the post.

    Add the notifiable trait

    Notifications can be sent in one of two ways. Either through the Notification facade or by adding the Notifiable trait to a model. The facade is recommended when you need to send a notification to multiple notifiable entities such as a collection of users.

    In this example, it’s only going out based on one item, so I added the trait to my Post model.

    use Illuminate\Notifications\Notifiable;
    class Post extends Model
    {
        use Notifiable;
    
    

    Sending your first notification

    Now, with everything setup and ready all that is left to do is send our first notification. Fetch a single item from the Model and then fire off the notification:

    $post = \App\Post::find(1);
    $post->notify(new \App\Notifications\PostPublished());
    

    If all is correct, you’ll see it instantly in your Telegram channel.

    With the setup of this site using WordPress as a backend when my syncing system runs and finds a creates a new Post it now automatically sends to Telegram and Twitter which I covered in a previous post.

    If you are a Telegram user join the @laravelnews group and I’ve created a simple Laravel sticker pack. It’s only two stickers but, hopefully, one day I’ll get to add more to it.

  •    Laravel v5.3.25 is released 

    Laravel has released v5.3.25 which includes two new validation rules, the ability to set the file permissions in the Filesystem, and a fluent builder for SlackMessageAttachmentField.

    New validation rules

    The two new validation rules included in v5.3.25 is a before_or_equal and after_or_equal which allows you to verify a date against a known value. Here is an example of validating a birthday is for someone over the age of 21:

    $this->validate($request, [
        'birthday' => 'required|date|before_or_equal:1995-11-30',
    ]);
    

    Then the opposite if you want to verify someone is under eighteen:

    $this->validate($request, [
        'birthday' => 'date|after_or_equal:1998-11-30',
    ]);
    

    Filesystem File Permissions

    The Filesystem now includes the ability to get or set the permissions of a file:

    $filesystem->chmod('file.txt'); // returns the chmod
    $filesystem->chmod('file.txt', 0777); // chmod 777 file.txt
    

    SlackMessageAttachmentField Fluent Attachments

    Slack supports longer form attachments and previously Laravel defaulted to the “short” style. With this new feature you can define all the fields that Slack allows:

    return (new SlackMessage)
        ->content('Content')
        ->attachment(function ($attachment) {
            $attachment
                ->title('Laravel', 'https://laravel.com')
                ->content('Attachment Content')
    
                //build up an attachment field
                ->field(function($attachmentField) {
                    $attachmentField
                        ->title('Special powers')
                        ->content('Zonda')
                        ->dontDisplaySideBySide();
                });
    
                //manually add one
                ->field('Project', 'Laravel')
        });
    

    Additional Changes and Bug Fixes

    There are a few more changes and fixes included in this release and you can read the full change log from GitHub. To grab the latest version just run composer update

  •    24 Pull Requests 

    24 Pull Requests is a project to promote open source collaboration during the month of December. The idea is to “Send 24 pull requests between December 1st and December 24th,” and it encourages developers to give back to open source with little gifts of code.

    This is the fourth year and there are currently 11,093 developers and 10,201 organizations participating. If you are new to open source or are a seasoned pro it’s a great way of supporting the community.

    Joe Ferguson, the creator of LaraTraining.com, has been participating since the beginning and I had the opportunity to interview him about it.

    What made you decide to start contributing to 24 Pull Requests?

    I ran across 24 Pull Requests in 2013 from my Twitter feed. I thought it was a cool idea and the angle they promote is “giving back little gifts of code for Christmas.” They also do a wonderful job at onboarding people who may not have ever contributed to open source software, let alone open a pull request. They also make it easy for seasoned veterans to find projects to contribute to. Once you sign up for an account, you can choose from a giant list of programming languages and they’ll give you related suggestions of things to work on. I found some really neat projects from their suggestions and met some awesome people. 24 Pull Requests is how I found out about Snipe-IT, an open source Asset Management project built on Laravel. I was happy to find a Laravel project since it was easy for me to jump into the code base and start offering help. The next year I met Mark Railton, an awesome developer who was working on a simple freelancing management application. He was building this app in part to scratch his own itch but also to further his development skills. I learned a lot working on that project and used it as a test case for learning the Codeception testing framework in depth.

    Has it helped improve your skills and knowledge?

    Absolutely. I’ve found projects I would have likely not found before and learned so much about how other OSS projects work. It’s also been interesting to see other developers solving problems in different ways. The first year I participated I was a solo developer at a company and still trying to figure out if I was the only one doing things a particular way. In recent years it’s empowered me to jump into languages and code I would normally be intimidated by, such as JavaScript. Because I’ve been able to contribute and get feedback via these pull requests I feel like I’ve gained so much in areas I was previously lacking in my skillset.

    Do you think it helps the projects you’ve contributed too?

    I’ve learned so many things, from automating code style checks via EditorConfig to how other developers handle Pull Requests and even conflict resolution. It has also taught me how to gracefully reject a pull request or an idea which just doesn’t seem to fit the project. I feel like I’ve been able to bring a lot of my experiences from 24 Pull Requests to the rest of my OSS work, especially the Phergie IRC Bot project where I am one of the maintainers. With Phergie we want to promote easy onboarding and a supportive environment. I learned from Chris Hartjes it’s important to thank people for submitting pull requests. He’s commented several times that as a project owner or maintainer it’s very important to thank and support your users and contributors. The grateful attitude I’ve seen him practice in his own OSS work is something I admire and really try to bring to my projects.

    What has been your biggest take away from the project?

    Be a good OSS contributor. Read the docs; if there aren’t any docs, then that is a great place to start. Make sure you read through issues and closed PRs, not all maintainers are the same. See how a project owner treats their contributors before you start contributing. Most are grateful but make sure you survey the area before you start contributing.

    For those that may have never submitted a PR before do you have any advice?

    Just do it! I was very intimidated at first and can empathize with those that are new to the process. Just give it a shot. No pull request is ever too small. No maintainer has ever seriously said, “I wish I didn’t have so many PRs to review.” Even if you’re not familiar with the languages or how the project works you can still contribute to the documentation. Does the project have a “getting started” guide? That’s easy to do, just pull down the project and get it up and running while documenting all the steps.

    My friend SammyK (@SammyK) wrote a useful guide on how to get started contributing to the documentation of the PHP project. I highly recommend the read.

    Also, the PHP community has an AMAZING resource in #phpmentoring on the Freenode IRC Network as well as https://php-mentoring.org. There are people out there wanting to be mentored and mentors offering their services to apprentices.

    Is it easy to get started on 24 Pull Requests?

    Certainly! Visit http://24pullrequests.com/ and click the “Log in with Github” link, authorize the application, and then you can view your dashboard and profile. Once you select programming languages from your profile, you’ll see relevant projects in the “my suggestions” section. Then every Pull Request you open from December 1-24th will be automatically added to your profile. If you are impatient like me, you can manually synchronize as well.

  •    Review of Test-Driven Laravel 

    I’ve been programming for close to a decade, and I’m constantly trying to find ways so to improve my skill set to be able to keep up with the ever-changing landscape of technology. The one area I’ve always wanted to improve in has been testing.

    I’ve joked on Twitter about using my HasAdamWathanOnTelegramForSupport trait to get help with things that were tricky to test. So when Adam announced at Laracon that he was creating a course on building real-world applications with TDD, I was really excited to see where it would go.

    Over the past couple of months, I’ve been lucky enough to preview the course as the lessons get finished. It’s been really helpful because I’ve been working on a large, complex application, and I’ve been able to apply the things I’m learning immediately in my day-to-day work.

    I’ve learned so much from this course already; everything from what tests to write first, how to refactor my tests to make them faster, starting new features with a failing test, and simplifying my tests with factories and states. The most helpful part so far has been learning how to add test coverage for the parts of my app that need to communicate with external services, such as Stripe. At this point, I’m comfortable enough writing tests that I’m actually adding new features to my project test-first, before writing any actual code.

    But I’ve also learned about more than just the mechanics of testing. I’ve learned how to evaluate my code and find ways to improve it through refactoring. If you’ve seen Adam’s talk Chasing “Perfect”, imagine that level of detail applied to an entire app. I’ve learned a lot about testing from the course, but I’ve learned just as much about writing well-designed object-oriented code. It’s definitely a course on building applications with TDD, not just a course on testing.

    Test-Driven Laravel has been a game changer for me, and I’m looking forward to watching the rest of the lessons as they become available. But I’m even more excited for everyone else to get their hands on the course, so we can all get better at testing as a community.

 最新レシピ

   scrutinizerCIを使って継続的インテグレーションと静的解析

  Solution / 2014年11月29日 23:46

   データベースをクエリービルダー、Eloquentを使用せずに操作したい

  DB / 2014年11月03日 16:31

   ページネーションを実装する

  Paginator / 2014年09月27日 22:09

   クエリー結果でページネーションを実装する

  DB / 2014年09月27日 22:09

   クエリー結果をキャッシュする

  DB / 2014年09月27日 22:09

   Bladeで @while を使用する

  Blade / 2014年09月27日 22:09

   データベースの接続先を変更する

  DB / 2014年09月10日 10:56

   ファサードクラス一覧

  Core Extension / 2014年09月10日 10:56

   Laravelプロジェクトでphpunitを利用する

  Testing / 2014年09月09日 00:49

   ファサードをモックする

  Testing / 2014年09月09日 00:49

   シンプルなサービスプロバイダーを作成する

  Service Provider / 2014年09月09日 00:49

   LaravelプロジェクトでTravis CIを使った継続的インテグレーション

  Solution / 2014年09月09日 00:49

   クロージャを利用したルーティングの作成

  Route / 2014年09月09日 00:49

   ミドルウェアについて理解する

  Middleware / 2014年09月09日 00:49

   簡単でシンプルなミドルウェアクラスを作成する

  Middleware / 2014年09月09日 00:49

   デフォルトの実行言語を設定

  Lang / 2014年09月09日 00:49

   翻訳を確認

  Lang / 2014年09月09日 00:49

   キーに対応する多言語翻訳文字列を取得する

  Lang / 2014年09月09日 00:49

   デフォルトで利用されている言語環境を取得する

  Lang / 2014年09月09日 00:49

   ロケール(言語)変更を検知する

  Lang / 2014年09月09日 00:49

   メッセージローダーにnamespaceを追加する

  Lang / 2014年09月09日 00:49

   XCacheをインストールする

  Installation / 2014年09月09日 00:49

   VirtualBoxをインストールする

  Installation / 2014年09月09日 00:49

   Vagrantをインストールする

  Installation / 2014年09月09日 00:49

   SQLiteをインストールする

  Installation / 2014年09月09日 00:49
このレシピサイトについて

このサイトはLaravel Recipesのレシピを日本語訳にしたものと、
日本独自のレシピを含んでします。
レシピの要望等がありましたら、お気軽にご連絡ください。
またこのサイトはオープンソースで公開されています。
Laravelの学習等にお役立てください
Laravel.JpRecipe

View all Packages for your Laravel projects