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

Video: Taylor Otwell covering new features for Laravel 5.3


Sending and Receiving SMS with Laravel and Nexmo

$
0
0

In this quick tutorial by Phil Leggetter, we’ll cover how you can both send and receive SMS from your Laravel application. We’ll do this using Nexmo, a cloud communications platform that offers APIs for provisioning phone numbers, sending and receiving SMS (which is handy since we’ll use that), making and receiving phone calls and more.

Prerequisites

You’ll need a Nexmo account, the Nexmo CLI (Command Line Interface) installed and setup, and your standard prerequisites for a Laravel app. You’ll also need a localtunnel option so that the Nexmo service can make an HTTP request to your local web server. We recommend ngrok.

Getting Started

With that in place let’s create our Laravel SMS application:

composer create-project --prefer-dist laravel/laravel laravel-sms
cd laravel-sms

Next, let’s add the Nexmo Laravel package to composer.json.

"require": {
    ...,
    "nexmo/laravel": "dev-master as 1.0",
    "nexmo/client": "dev-master as 1.0"
},

Note that when these packages come out of beta, you’ll only need to include the nexmo/laravel package and nexmo/client will be brought in as a dependency.

Add the Nexmo Service Provider to your app.php config:

'providers' => [
    ...,
    Nexmo\Laravel\NexmoServiceProvider::class
]

Note: that you can also add to aliases if you want to use the facade.

Install the packages and copy over the Nexmo configuration file:

› composer update
php artisan vendor:publish

Finally, add your Nexmo API Key and API Secret to /config/nexmo.php, updating the API_KEY and API_SECRET values based on the those found in the API settings in the Nexmo Dashboard.

'api_key' => 'API_KEY',
'api_secret' => 'API_SECRET',

Note: you can obviously set these value from your .env and env(...) if you prefer.

Sending an SMS

Note: for simplicity we’ll add all functionality directly to the app/Http/routes.php file.

Add the following route to app/Http/routes.php:

Route::get('/sms/send/{to}', function(\Nexmo\Client $nexmo, $to){
    $message = $nexmo->message()->send([
        'to' => $to,
        'from' => '@leggetter',
        'text' => 'Sending SMS from Laravel. Woohoo!'
    ]);
    Log::info('sent message: ' . $message['message-id']);
});

You’ll notice that in the above code the from value is set to a string with the value of @leggetter. This will work in the UK, but may not work in other countries. It really depends on the country.

nexmo-receiving-sms

For those of you that need to use a real number here, and for everybody else who’ll need a real number for the next step, let’s look at either using an existing number or buying one.

Listing, Searching and Renting Numbers

One of the prerequisites for the tutorial was the Nexmo CLI. We can use this to do a whole bunch of things including working with phone numbers (Virtual Numbers to be precise) that are associated with our account. If you haven’t already done so you should install and setup the CLI where API_KEY and API_SECRET should be replaced with the API credentials you used earlier:

› npm install -g nexmo-cli
nexmo setup API_KEY API_SECRET

We can now list numbers that we’re already renting, search for numbers that are available to rent, rent those numbers or cancel the rental. Let’s start by seeing if we have any numbers associated with our account:

› nexmo number:list
14155550123

In the above example, I have a number. If you don’t have a number, you can search for numbers to rent. All you need to know to do that is the two character ISO 3166-1 alpha-2 country code. It’s easier than it sounds. For example, for Great Britain it’s GB and for the United States it’s US. Let’s search for a number to rent in the US:

› nexmo number:search US
14155550111
14155550222
14155550333

If you don’t have a number, you should buy one so that you can send an SMS in countries that require a real outbound number and so that we can also receive SMS later on.

› nexmo number:buy 14155550111 --confirm
Number purchased: 14155550111

Really Sending an SMS

Now if you update your code to use the number you’ve just purchased. Replace the from value with the real number you’ve just purchased or load the number in using env('NEXMO_NUMBER') as we have below:

Route::get('/sms/send/{to}', function(\Nexmo\Client $nexmo, $to){
    $message = $nexmo->message()->send([
        'to' => $to,
        'from' => env('NEXMO_NUMBER'),
        'text' => 'Sending SMS from Laravel. Woohoo!'
    ]);
    Log::info('sent message: ' . $message['message-id']);
});

Then start the server:

› php artisan serve
Laravel development server started on http://localhost:8000/

And navigate to http://localhost:8000/sms/send/YOUR_NUMBER where YOUR_NUMBER should be replaced with your real number including the country code in a e.164 format, the same format that has been shown in all the examples above.

If you check storage/logs/laravel.log you will see a log entry related to the message that has just been sent with a unique message-id at the end of the log entry e.g.

[2016-08-02 13:45:01] local.INFO: sent message: 03000000068F5D97  

Receiving an Inbound SMS

For the Laravel application to receive an SMS we need to do a few things:

  1. Ensure our application is reachable by Nexmo using a localtunnel
  2. Create a route to be called when receiving an SMS
  3. Disable CSRF for our SMS receiving route
  4. Inform Nexmo where to make a webhook call to when a message is received

Let’s start by making our application reachable by the Nexmo platform. Assuming you’re using ngrok and your Laravel web server is listening on port 8000 you can do this as follows:

› ngrok http 8000
ngrok by @inconshreveable                                                (Ctrl+C to quit)

Tunnel Status                 online
Version                       2.1.3
Region                        United States (us)
Web Interface                 http://127.0.0.1:4041
Forwarding                    http://814882e9.ngrok.io -> localhost:8000
Forwarding                    https://814882e9.ngrok.io -> localhost:8000

Connections                   ttl     opn     rt1     rt5     p50     p90
                              0       0       0.00    0.00    0.00    0.00

As you can see from the above output from ngrok, a subdomain on ngrok has been created, and any requests to that will now be forwarded on to localhost:8000.

With the localtunnel in place we should now create a route to receive the SMS in routes.php:

Route::post('/sms/receive', function(\Nexmo\Client $nexmo){
});

By default, Laravel won’t allow POST requests to this route without a CSRF token. Since the request to this route will be made by Nexmo, which won’t have a token, we’ll disable CSRF for this route. Add this in App/Http/Middleware/VerifyCsrfToken.php:

protected $except = [
    '/sms/receive'
];

Finally, let’s inform Nexmo where to make the webhook call to when an SMS is received on our number. We can do this using the Nexmo CLI. When executing the following command you should use the phone number you have rented from Nexmo and your ngrok subdomain:

› nexmo link:sms 14155550111 https://814882e9.ngrok.io/sms/receive
Number updated

When you execute this command, the Nexmo service will attempt to call your /sms/receive route, and you should see those requests in your ngrok terminal.

HTTP Requests
-------------

POST /sms/receive              200 OK

If you see anything other than a 200 response, then you’ll need to fix that for the number and webhook association to successfully complete.

The Nexmo PHP Client library provides a way of easily capturing the HTTP parameters that have been sent by Nexmo to the Laravel application and creating an InboundMessage message object that we can work with. Update the /sms/receive code as follows:

Route::post('/sms/receive', function(\Nexmo\Client $nexmo){
    $message = \Nexmo\Message\InboundMessage::createFromGlobals();
    Log::info('got text: ' . $message->getBody());
});

Then send an SMS to your rented number and check storage/logs/laravel.log where you will see your message body logged.

[2016-08-02 13:45:01] local.INFO: sent message: 03000000068F5D97  
[2016-08-02 14:20:50] local.INFO: sent message: 0300000006917797  
[2016-08-02 14:21:17] local.INFO: got text: Sending one back.

nexmo-receiving-sms

Auto-Replying to an Inbound SMS

Finally, let’s create an auto-responder to the inbound message. The Nexmo PHP Client provides a nice way of doing that using the InboundMessage->createReply function:

Route::post('/sms/receive', function(\Nexmo\Client $nexmo){
    $message = \Nexmo\Message\InboundMessage::createFromGlobals();
    Log::info('got text: ' . $message->getBody());
    $reply =$nexmo->message()->send($message->createReply('Laravel Auto-Reply FTW!'));
    Log::info('sent reply: ' . $reply['message-id']);
});

Send a message to your rented number and you’ll get an auto-reply. It’s not quite magic, but it’s pretty close!

nexmo-sms-auto-reply

Conclusion

In this tutorial, we’ve covered everything you need to know to add sending and receiving SMS, and even auto-replying, to your Laravel application using the Nexmo cloud communications platform.

You can find the code for this sample via github.com/nexmo-community/laravel-sms.

Please don’t hesitate to get in touch with any thoughts or feedback. You can get in touch via email using devrel@nexmo.com or contact me on Twitter via @leggetter.

If you do follow this tutorial through and would like some addition credit, please drop us an email with your Nexmo API Key (not secret), tell us you saw this on Laravel News, and we’ll add some more credit to your account.


Many thanks to Nexmo for sponsoring Laravel News this week and for sharing this tutorial on how to get started using their service.

Welcome to the next version of Laravel News

$
0
0

Four years ago Laravel News got its start as a simple Twitter and Facebook account where I would share things created by the Laravel community and try to help out the creators as well as users find new awesome stuff. From there it transitioned into a Tumblr site and finally into a full website that’s been running for the past three years.

Back in May Laravel announced that Laravel News would be the official Laravel blog and I didn’t like how my current design looked amateurish compared to the rest of the Laravel sites. To remedy that I partnered up with Zaengle who helped take my ideas and turn it into something that I am extremely happy with and proud to bring to the community.

During this move, I have redone the way the site is powered. Previously it ran on WordPress with a custom theme I put together, it worked fine but added new features, and sections became harder and harder, and I wanted the ability to use what I am comfortable with, Laravel. However, I didn’t want to give up the media library and editing experience of WordPress.

So to have the best of both worlds I kept the old site on WordPress and used the WP Rest API paired with the Laravel Scheduler. This allows me to automatically sync data from WordPress into my database without having to rebuild an entire CMS admin area. I have the same setup for the podcast section, and it hooks into the Simplecast API to pull those over.

I’m sure you think this is crazy and it might be but if you are interested in how it all works here is a tutorial on how I use WordPress as the backend. I’m pretty confident only a site ran by a developer would like this setup.

While I was working on all this, I didn’t have time to finish all the sections of the new site. You may notice the community links are missing, and the search is hit or miss. I decided to roll out without these features and will be adding links back soon and better searching once 5.3 is released with Laravel Scout.

I hope you like the new site as much as I do, and I want to thank you all.

P.S. If you spot any errors or problems I setup a new bugs repo where you can submit it.

Laracon EU – Interview with speaker Freek Van der Herten

$
0
0

This year’s Laracon EU has a fantastic speaker lineup including twenty-two speakers from all across the world. Tickets are still available and it’s one you will not want to miss.

Freek Van der Herten (@freekmurze) is one of those speakers and he graciously took a break from releasing new packages to allow me the opportunity to ask him a few questions about his talk and the conference experience.

Is this your first Laracon EU?

No, I’ve been the last year’s edition as well and I had a blast there. To be honest it was the best conference I’ve ever been to. The people, the talks, the venue, … it was incredible. The bar is set very high for this edition.

How far away are you from Amsterdam?

I live in Belgium, which is a neighboring country of The Netherlands. From my hometown, Antwerp, Amsterdam is only 2 or 3 hours away by train.

Your Laravel backup package seems to be popular is that what you are going to be giving a talk on?

I’ll dedicate quite some time of my talk to introducing the package. I’ll demonstrate what it can do. Since we’re going to be in a room full of developers I’ll also show the inner workings of the package. But aside from that I’ll also touch on the pitfalls and best practices regarding backups in general and highlight some good backup solutions.

Should everyone be using a backup system outside of what hosting companies provide?

Unless you have a dedicated ops person/team that takes care of backups, you as a developer should definitely take care of your own backups in addition to what your hosting company provides. Take DigitalOcean for example: they provide backups, but they only take a snapshot once a week. So if you solely rely on their backups you could potentially lose data for several days. Most cloud providers store their backups in the same datacenter as your servers. So if the datacenter is down, the backups are unavailable. These are all good reasons to take care of backups yourself.

What other talk are you most excited about?

Sorry, it’s just too difficult to name a single speaker here. I’m looking forward to seeing two my fellow Belgians speaking: Hannes Van de Vreken will talk about cool stuff you can to with the IoC container, Mattias Geniar will explain how Varnish can be used to speed up a site. Also, high on my list is Gabriela D’Avila who will talk about making the most with MySQL 5.7

Any other words of encouragement for those coming to Laracon?

I’m a big fan of uncon’s at conferences and I’m happy this edition of Laracon EU will have one. If you’re not familiar with an uncon, it’s just a room at a conference where everybody is allowed to give a talk. Usually, there’s a big notepad with the schedule in front of the room where you can write down your name and subject of the talk. If you want to learn how to give a talk in public an uncon session is the perfect playground.

Be sure to socialize a bit with your fellow artisans between the talks. It’s incredible how much you can learn from everybody.

And last but not least: just have fun!

DreamFactory – Turn any database into an API Platform (Sponsor)

$
0
0

DreamFactory auto-generates a rich API platform from nearly any SQL or NoSQL database. In addition to automatically generating REST endpoints for data and schema, DreamFactory offers parameters for complex filters, virtual foreign keys, aggregation, and much more.

df-main-infographic-700px

Built on the Laravel framework, DreamFactory is feature-rich backend solution for real world application development. Instant APIs let you build and iterate fast and the Apache license allows for wide distribution.

healthcare-app

DreamFactory Gold is an enterprise solution for fully realized developer ecosystems offering granular user and resource management along with exceptional support direct from our engineering team.

Recent blog posts:

Try it out now on our free hosted system or dig deeper into the possibilities with robust documentation and sample apps for a wide array of front-end destinations.

Laravel Notifications – Easily send quick updates through Slack, SMS, Email, and more

$
0
0

Laravel Notifications is an all new feature coming to Laravel 5.3 that allows you to make quick notification updates through services like Slack, SMS, Email, and more.

Let’s see how easy it is to build and send a notification using this new feature:

class NewPost extends \Illuminate\Notifications\Notification
{
    public function __construct($post)
    {
        $this->post = $post;
    }

    public function via($notifiable)
    {
        return ['database'];
    }

    public function toArray($notifiable)
    {
        return [
            'message' => 'A new post was published on Laravel News.',
            'action' => url($this->post->slug)
        ];
    }
}

All you need to do now is to send the notification to the selected users:

$user->notify(new NewPost($post));

Creating Notifications

Laravel 5.3 ships with a new console command for creating notifications:

php artisan make:notification NewPost

This will create a new class in app/Notifications, each notification class contains a via() method as well as different methods for building notifications for different channels.

Using the via() method you can specifying the channels you’d like this particular notification to be sent through, check this example for the official documentation website:

public function via($notifiable)
{
    return $notifiable->prefers_sms ? ['sms'] : ['mail', 'database'];
}

The via method receives a $notifiable instance, which is the model you’re sending the notification to, in most cases it’ll be the user model but it’s not limited to that.

Available channels are: mail, nexmo, database, broadcast, and slack.

Formatting Email Notifications

You can format how notifications are sent through different channels, for instance, let’s take a look at formatting a mail notification:

public function toMail($notifiable)
{
    return (new MailMessage)
                   ->subject('New Post!')
                ->line('A new post was published on Laravel News!')
                ->action('Read Post', url($this->post->slug))
                ->line('Please don\'t forget to share.');
}

This will create a mail message using a nice built-in responsive template that you can publish using the vendor:publish console command.

The notification system will automatically look for an email property in your model, however, you can customise this behaviour by defining a routeNotificationForMail in your Model and return the email address this Model will be contacted on.

Formatting Nexmo SMS Notifications

Same as in the case of an email notification, you need to define a toNexmo method in your notification class:

public function toNexmo($notifiable)
{
    return (new NexmoMessage)
        ->from(123456789)
        ->content('New post on Laravel News!');
}

In the case of Nexmo notifications, laravel will look for a phone_number property in the model. You can override that by defining a routeNotificationForNexmo method.

You can set a global from number in your Nexmo configuration file, that way you won’t have to provide a from number in each notification.

Formatting Database Notifications

To Format a database notification you may define a toDatabase method:

public function toDatabase($notifiable)
{
    return new DatabaseMessage([
        'message' => 'A new post was published on Laravel News.',
        'action' => url($this->post->slug)
    ]);
}

To start using the database channel you may read the full documentation on the official website.

Sending Notifications

You can send notifications using the notify() method on your model, this method exists on the Notifiable trait which you’ll need to add to your Model.

$user->notify(new NewPost($post));

You can also use the Notification facade, this will allow you to send notifications to multiple notifiables at the same time:

Notification::send(User::all(), new NewPost($post));

Queueing Notifications

You can easily queue sending notifications by using the ShouldQueue interface on the Notification class and including the Queueable trait.

<?php

namespace App\Notifications;

use Illuminate\Bus\Queueable;
use Illuminate\Notifications\Notification;
use Illuminate\Contracts\Queue\ShouldQueue;

class NewPost extends Notification implements ShouldQueue
{
    use Queueable;
}

The Laracon US Recap Episode

Laracon EU is almost sold out.

$
0
0

Laracon EU is almost sold out and this is your last chance to get tickets and attend the conference. The conference is going to be August 23rd and 24th which is only about two weeks away.

If you purchase in the next three days you can lock in the €399 ticket price, if not then last-minute pricing goes into effect which is €499 and there is no guarantee those are even going to be available.

This is your last chance to attend this year’s Laracon EU and if you are on the fence you should act fast before it’s to late.


Laravel Mailable: The new and improved way to send email in Laravel

$
0
0

A new feature in Laravel 5.3 is a way to simplify sending email by creating “mailable” classes that handle setting up your emails.

The best way to explain this feature is with an example. In Laravel 5.2 you would typically send an email like the following that is outlined in the documentation:

Mail::send('emails.reminder', ['user' => $user], function ($m) use ($user) {
    $m->from('hello@app.com', 'Your Application');
    $m->to($user->email, $user->name)->subject('Your Reminder!');
}); 

A lot is going on in those four lines of code. You pass a view, data to assign to the view, use the “user” in the closure, and finally setup your message.

Now in Laravel 5.3 you can simplify this by utilizing a “mailable” class.

php artisan make:mail YourReminder

Next, open the new class that is created and all of a mailable configuration is done in the build method. Within this, you may call various methods such as from, subject, view, and attach to configure the email’s presentation and delivery. Here is a minimal example:

public function build()
{
    return $this->from('example@example.com')
        ->view('emails.reminder');
}

Now, anytime you want to send this email you can call it like this:

Mail::to($email)->send(new YourReminder);

All of the existing mail features still work. You can queue, add cc, bcc, attach files and more.

If you’d like to learn more about Laravel Mailable here are a few resources to help you on your journey:

Easily Integrate HTTP/2 Server Push with a Laravel Middleware

$
0
0

As we all know technology changes fast and if you don’t stop and look around once in awhile, you could miss it. HTTP/2 is one area of our tech stack that I haven’t been keeping up with an honestly knew nothing about it until Laracon where Ben Ramsey gave a talk on the subject.

You can watch his talk here and his slide deck is available from his site to browse through. What amazed me is how easy it seemed to implement by utilizing server push or preload. Basically, you send a special “Link” header with all the pages assets and then if the server and browser support it they are pulled down in a more efficient use of the network.

During Ben’s talk he gave an example usage of how this could work in Laravel and here is one way:

return response($content, $status)
->header('Link', '; rel=preload; as=style', false)
->header('Link', '; rel=preload; as=script', false);

Of course doing this for every single asset is kind of a pain. Luckily we have two Laravel packages available that will automatically handle this through the Middleware.

The first is by Tom Schlick and the second by Jacob Bennett. Both packages do basically the same thing but each have a different idea on how you would want to integrate it.

Tom’s automatically includes the resources in your elixir /build/rev-manifest.json file. Then to add a resource manually you use

pushStyle($pathOfCssFile);
pushScript($pathOfJsFile);
pushImage($pathOfImageFile);

Jacob’s, on the other hand, is more automated because it scans the DOM and automatically adds any script, style, or image into the headers.

Which one you choose is going to be dependent on your project and your ideal workflow. Jacob’s is set it and forget it style but the view must be scanned to grab all the assets out. Where Tom’s is more manual but you can control every aspect.

If you are looking to improve the performance of your Laravel app give these a try.

All of the Laracon videos are now available for free

$
0
0

StreamACon has just published all of the videos from Laracon US and they are available for everyone to watch for free.

Included with all the talks is also videos from the sponsor segments so you can relive the entire conference right from your couch. Except of course mingling with everyone. :)

New Community Project: Laravel Notification Channels

$
0
0

Laravel 5.3 will ship with a notification system that includes a Nexmo SMS driver, a Mail driver, and the ability to include custom drivers. Now that we have this system built-in we can use the new Pusher service from inside our Laravel applications.

All we need to do is to create a custom driver and that’s it, we’ll be able to send Push notifications to our Mobile devices right away.

With the help of Freek Van der Herten and Marcel Pociot we managed to build an easy to use driver for Pusher Push Notifications.

Pusher, a real-time communication platform, has recently introduced an all-new FREE service for application developers, it’s a unified API to send native Push Notifications to iOS and Android devices.

Using native Push Notifications allows you to communicate with your users even when the app is closed or inactive, this has a great effect on user engagement.

Being able to send iOS and Android Push Notifications using a unified API saves the hassle of having to apply multiple setup procedures. All you have to do is to upload your APNS certificate for iOS devices or add your GCM API key for android devices, and that’s it.

Using this driver you’ll be able to send push notifications like this:

class AccountApproved extends Notification
{
    public function via($notifiable)
    {
        return [Channel::class];
    }

    public function toPushNotification($notifiable)
    {
        return (new Message())
            ->iOS()
            ->badge(1)
            ->sound('success')
            ->body("Your {$notifiable->service} account was approved!");
    }
}

This driver will allow you to send Push Notifications with a fluent expressive Laravel-style syntax.

You may check it out here.

Building custom drivers

There are many platforms that send notifications, and with the new system in Laravel 5.3 we believe that it’s a good idea to collect all the custom drivers in a single place, just as socialiteproviders.github.io is a one-stop-shop for all Socialite Providers, for that we created a GitHub organization where we’ll collect and host all custom drivers.

It’s still in the making but contributions are most welcomed if you have an idea for a custom channel, please check this skeleton repo where you can use as boilerplate.

A Quick Guide to Choosing Tools (Sponsor)

$
0
0

What separates the wrong analytics tool from the right one? It’s easy enough to figure out — if you understand the job you’re trying to get done.

That’s how you need to think about your tools: in terms of the jobs to be done. Your tools are a means to an end, not an end unto themselves. Think about the job you want to get done right now. Are you trying to drive users to your site? Increase your conversion rate? Well, if you ARRRen’t sure, you can use Pirate Metrics to break down the different steps of a customer lifecycle.

Pirate Metrics is an acrostic developed by 500 Startups to help companies have a clear list of jobs that drive growth.

  • Acquisition: Drive users to your site through various channels and get them to sign up.
  • Activation: Engage users early on by having them participate with your most important feature(s).
  • Retention: Get users to come back, visit and use your product multiple times.
  • Referral: Leverage users who are jazzed about your product to refer others.
  • Revenue: Convert users to pay you money for your services.

If you’re trying to figure out market fit, you’re probably focused on retention and understanding what makes people stick around. This will take a combination of analytics and customer feedback tools.

If you’ve achieved fast growth, you’re likely working on maintaining your growth rate and managing your customer success workflow. This is where optimizing behavioral email campaigns and choosing sustainable ticket systems becomes important.

No matter where you choose to focus, there are a lot of tools out there that can help you get these jobs done. There are tools out there that can help you optimize your conversion and advertise more effectively to acquire customers; tools that can help you analyze your funnel to drive activation; tools that can help you send push notifications and NPS surveys to retain customers; tools that help you manage customer relationships to help you drive revenue; and tools to manage referrals to encourage word of mouth conversions.

The important thing is to start small and be realistic. You can’t focus on every area of growth at the same time. Start by choosing your goals, and work backwards from there to narrow down on which area to focus. You can then concentrate on using tools to achieve one or two goals instead of introducing a bunch of tools at once.

Implementing tools takes time, and sometimes, the tool that helped you achieve a goal a year ago is no longer a tool your business needs. Changing tools can be tricky, since it takes a lot of engineering hours to implement a tool, and different teams might be competing for engineering time to prioritize the new tool they need.

That’s where Segment comes in. Use Segment to try several tools, with demos using with your actual customer data, and with minimal loss of engineering time turning tools on and off. Try Segment today.

Many thanks to Segment for sponsoring the site this week. Sponsored via Syndicate Ads.

Laravel Scout is now open for developer testing

$
0
0

Laravel Scout is a driver based full-text search for Eloquent that is going to be available when Laravel 5.3 launches.

The driver is not officially released yet, however, the repository is now live and available for those that want to play with more engines.

Taylor said he would be working on docs this week in anticipation of the official 5.3 release and this first release should only be used in testing until it’s officially launched.

For those not familiar with Scout it is an optional package that makes full-text searching simple.

Scout works by implementing a “Searchable” trait with your existing models. Then it’s just a matter of syncing the data with the search service like this:

php artisan scout:import App\\Post

After that you can search your models with:

Post::search('Alice')->get();

You can even paginate:

Post::search('Alice')->paginate()

And it even includes simple where clauses:

Post::search(‘Alice’)—>where('acount_id', '>', 1)->paginate()

The repository has already had a few pull requests for adding additional search engines and Taylor is recommending developers create their own packages like what is being done with Laravel Notifications.

Once 5.3 is official the documentation for Scout will be available and it’ll be ready for all.

TNTSearch Driver is now available for Laravel Scout

$
0
0

Laravel Scout was just opened for developer testing and TNTStudio has already launched a new package for implementing their TNTSearch into Scout.

TNTSearch is full-text search engine written in PHP with no dependencies. For more information on how it works, they have a tutorial on building and searching an index.


How to use WordPress as a backend for a Laravel Application

$
0
0

Last week I relaunched Laravel News, and the new site is running on Laravel with WordPress as the backend. I’ve been using WordPress for the past two years, and I’ve grown to enjoy the features that it provides. The publishing experience, the media manager, the mobile app, and Jetpack for tracking stats.

I wasn’t ready to give these features up, and I didn’t have the time to build my own system, so I decided to keep WordPress and just use an API plugin to pull all the content I needed out, then store it in my Laravel application. In this tutorial, I wanted to outline how I set it all up.

Please keep in mind there are several different ways of doing this, and you can take a look at the WordPress and Laravel post for a list of third party packages and resources that others have created to solve this same task. The primary options are to either hook into the WordPress database, pull from the API, or sync data from one system to the other.

I choose the sync option because I wanted everything separated. While researching I came across a package called WordPressToLaravel that does this, however, it only works with the wordpress.com hosted sites.

I decided to create my own system for working with a self-hosted WordPress install. This method requires more work up front, but it allows my site to be a typical Laravel application that I can easily improve and extend as needed.

Once I had it syncing content, I then set it up as a recurring task through the Laravel Scheduler, so it’s completely automated.

My setup is also entirely custom for my needs. I only wanted to pull posts, categories, and tags. Pages and other sections are all driven by either static Blade files or other API’s.

Let’s go through how this all works.

WordPress API

WordPress doesn’t ship with an API; however, the community has built a plugin named WP Rest API that allows any blog to have a jSON API.

In my case, I’m doing read-only requests that do not require any authentication. That makes reading and fetching data easy and simplifies a lot of code.

Here is my basic class to fetch a list of posts:

class WpApi
{
    protected $url = 'http://site.com/wp-json/wp/v2/';

    public function importPosts($page = 1)
    {
        $posts = collect($this->getJson($this->url . 'posts/?_embed&filter[orderby]=modified&page=' . $page));
        foreach ($posts as $post) {
            $this->syncPost($post);
        }
    }

    protected function getJson($url)
    {
        $response = file_get_contents($url, false);
        return json_decode( $response );
    }
}

Now when you call WpAPI->importPosts() it will grab the first page of results. The query string is worth mentioning because it has a few special clauses. The first is _embed which will embed all the extra data like image embeds, categories, and tags. Next is a filter to order by last modified that way when you edit a post on WordPress it is then on the first page of results, meaning it’s resynced.

Next, we need the ability to sync the post with our database. Here is how I set it up:

protected function syncPost($data)
{
    $found = Post::where('wp_id', $data->id)->first();

    if (! $found) {
        return $this->createPost($data);
    }

    if ($found and $found->updated_at->format("Y-m-d H:i:s") < $this->carbonDate($data->modified)->format("Y-m-d H:i:s")) {
        return $this->updatePost($found, $data);
    }
}

protected function carbonDate($date)
{
    return Carbon::parse($date);
}

For this step, I added a wp_id field to my own Posts table that way I have a one to one between my local database and WordPress.

Next, I just check and see if it doesn’t exist, then create it. Otherwise, update it, if it’s been modified since it was originally synced.

The createPost and updatePost are typical Laravel Eloquent inserts or updates. Here is the code for create:

protected function createPost($data)
{
    $post = new Post();
    $post->id = $data->id;
    $post->wp_id = $data->id;
    $post->user_id = $this->getAuthor($data->_embedded->author);
    $post->title = $data->title->rendered;
    $post->slug = $data->slug;
    $post->featured_image = $this->featuredImage($data->_embedded);
    $post->featured = ($data->sticky) ? 1 : null;
    $post->excerpt = $data->excerpt->rendered;
    $post->content = $data->content->rendered;
    $post->format = $data->format;
    $post->status = 'publish';
    $post->publishes_at = $this->carbonDate($data->date);
    $post->created_at = $this->carbonDate($data->date);
    $post->updated_at = $this->carbonDate($data->modified);
    $post->category_id = $this->getCategory($data->_embedded->{"wp:term"});
    $post->save();
    $this->syncTags($post, $data->_embedded->{"wp:term"});
    return $post;
}

If you look carefully, there are a few special cases like the author, featured image, category, and tags. Those come from the _embed in the original query string and syncing that data is just a matter of doing the same thing as previous.

public function featuredImage($data)
{
    if (property_exists($data, "wp:featuredmedia")) {
        $data = head($data->{"wp:featuredmedia"});
        if (isset($data->source_url)) {
            return $data->source_url;
        }
    }
    return null;
}

public function getCategory($data)
{
    $category = collect($data)->collapse()->where('taxonomy', 'category')->first();
    $found = Category::where('wp_id', $category->id)->first();
    if ($found) {
        return $found->id;
    }
    $cat = new Category();
    $cat->id = $category->id;
    $cat->wp_id = $category->id;
    $cat->name = $category->name;
    $cat->slug = $category->slug;
    $cat->description = '';
    $cat->save();
    return $cat->id;
}

private function syncTags(Post $post, $tags)
{
    $tags = collect($tags)->collapse()->where('taxonomy', 'post_tag')->pluck('name')->toArray();
    if (count($tags) > 0) {
        $post->setTags($tags);
    }
}

For the category I am pulling out the first category the post is assigned to because I only want one post per category, then in syncTags, I’m utilizing the Tags package by Cartalyst.

Creating a Scheduled Command

The final step to complete the import is to build a scheduled task to automatically pull posts down. I created a command named Importer through Artisan:

php artisan make:console Importer

Then in the handle method:

$page = ($this->argument('page')) ? $this->argument('page') : 1;
$this->wpApi->importPosts($page);

Finally, in Console/Kernel set this to run every minute:

$schedule->command('import:wordpress')
    ->everyMinute();

Now every minute of every day it attempts to sync the data and either create, update, or ignore the posts.

Going Further

This is a basic outline in how I set this feature up, and it only scratches the surface on what all could be done. For example, I’m heavily caching all the DB queries within the site and during this sync process if something is updated then the related cache is cleared.

I hope this helps show you that utilizing WordPress as a backend is not that hard to manage and at the same time gives you tons of benefits like creating posts from mobile, using it’s media manager, and even writing in Markdown with Jetpack.

Laravel 5.3 RC1 is now released

$
0
0

Laravel 5.3 has been under heavy development and we’ve all been waiting for the release with great anticipation. The first release candidate is now released and available for everyone to start testing.

You can grab the latest in a project by running:

laravel new demo-site --dev

The documentation is also completely updated for this version and the official release date is scheduled for next week at Laracon EU.

As with all early releases keep in mind that things can change, break, and nothing is guaranteed.

Laravel Passport – Easily setup your own OAuth2 server

$
0
0

Creating your own OAuth server can be difficult and Laravel 5.3 comes with a free optional package called Passport that is a full OAuth2 server that is ready to go in minutes.

Taylor demoed this new package during his Laracon talk and it was amazing seeing just how quick you can add this to your app. Today, he visited Laracasts and created a 15-minute overview video.

If you want to learn even more checkout the documentation and Matt Stauffer’s coverage.

Podcast: Laracon EU Special Edition

Podcast: Interview with Mike Bronner about his early experiences with Laravel Spark

$
0
0

Jack reads the news and interviews Mike Bronner while Eric takes a much needed week off.

  • Eric sent out his 100th episode of the Laravel News Newsletter!
  • Interview with Mike Bronner (@mikebronner) who shares his experiences being one of the first users to get Spark into production.
  • Mike talked about larachat live @larachatlive that meet Thursdays at 7pm CST
  • ViewJS 2.0
  • PHP RFC: Pipe operator

Book updates:

Tutorials:

Packages:

Viewing all 1751 articles
Browse latest View live