Visit the new website jadjoubran.io

Blog moved to Medium

I moved the blog to Medium. You can still see my previous & upcoming conferences on this site.


The story of Laravel & Angular material starter

Today I’m writing because Laravel & Angular material starter has reached 1,000 stars on github!

It’s now one of the top 250 PHP projects on github. And the screencasts have just surpassed 10,000 views! :rocket:

I would like to take this opportunity to thank all the contributors on the project. Especially those who have recently contributed to 3.1 and 3.2:

Also all the other contributors who have been asking questions and discovering bugs on Github!

How it started

A few months ago, I was building a commercial project for a client. I needed to use Laravel for sure.
But I also wanted to use Angular to make the UI reactive & I was particularly interested in the powerful components offered by Angular Material.

After spending over 40 hours on the setup for Laravel & Angular (which by the way, wasn’t that good), I noticed that open sourcing this setup would benefit a lot of users.

A few weeks later, it got featured on Laravel News. Since then, people started opening issues and tinkering with it.

The top priority has been to provide people with best practices for Angular apps that use a Laravel API. I can’t claim that it’s perfect, so if you have some feedback make sure to open a new issue!

What’s next

In a couple of weeks, version 3.2 will be out. It will feature out of the box JWT Authentication and password resets. Here’s what has been added so far.

I’m also working on better documentation by adding beginner friendly installation and more screencasts.

What about Angular 2?

Angular 2 is just around the corner. Hence the next logical step is to start working on Angular 2 with typescript support. This will become a priority as soon as 3.2 is released!

Anonymous survey

Community feedback has always been very important. That’s why I put together a 1 minute anonymous survey. No name, no email. I would love to know more how you’re using this starter project and how it can be improved.

Anonymous survey

:heart:


If you like this post, you can share it with your followers.

Angular error interceptors

After introducing response macros for Laravel APIs, it’s time to keep our angular code DRY.

Most modern web apps consume APIs frequently. Knowing that, we need to avoid writing the same code on every single API call.

Restangular

We will use Restangular to perform our API calls. Restangular is a wrapper on top of $http. You can write your own error interceptors using $http.

Setup

Below is the setup for an API service based on Restangular, written in ES6.

export class APIService {
  constructor(Restangular, ToastService) {
    'ngInject';

    var headers = {
      'Content-Type': 'application/json',
      'Accept': 'application/x.laravel.v1+json'
    };

    return Restangular.withConfig(function(RestangularConfigurer) {

      RestangularConfigurer
        .setBaseUrl('/api/')
        .setDefaultHeaders(headers)
        .setErrorInterceptor(function(response) {

          if (response.status === 422) {
            for (var error in response.data.errors) {
              var error_message = response.data.errors[error][0];
              return ToastService.error(error_message);
            }
          }

        });
    });
  }
}

As you can see, we start by setting the baseUrl to avoid writing /api/ on every single request.

Then we’re setting some default headers. We’re sending an accept header as part of the content negotiation process. But that’s outside the scope of this article. (Let me know in the comments if you’d like to have an article on content negotiation using dingo/api)

Then we’re setting an error interceptor. Which is a function that gets called every-time the API call encounters an error.
We can then extract the response status and perform specific actions based on it.
We know for sure that Laravel returns a response status of 422 whenever the validation fails. That’s how we’re able to show the first error message that we get from the API.
By the way, ToastService is just a helper service that opens Toast messages (using Angular Material).

Usage

Querying our API can now be done as following:

API.all('products').post({title, price}).then( (response) => {
  var user = response.data.user;
});

There’s no need to write the error function anymore, because that’s being handled by the error interceptor. We know that if the title for example doesn’t validate correctly, we’ll automatically get a toast message saying that.

What if …

What if for a specific scenario, you need to perform another action? That’s easy. Just pass in your custom error handler as the second argument for the then function.

API.all('products').post({title, price}).then( (response) => {
  var user = response.data.user;
}, (response) => {
    //response.status
    //response.data
});

Note that this action will be performed as well as the error interceptor.

Prefer a screencast?

This topic is also discussed in the below screencast


If you like this post, you can share it with your followers.

Laravel Response Macros for APIs

I would like to show you a use case for response macros when building an API with Laravel.

Dealing with APIs

Consistency is one of the most important aspects to consider when building an API. You often find yourself returning 2 types of responses; one for success and one for errors.

<?php

class PostsController
{
  public function get()
  {
    try {
      //some code
    }catch (Exception $e){
      //error
      return [
        'errors'  => true,
        'message' => $e->getMessage()
      ];
    }

    $posts = Post::get();
  
    //success
    return [
      'errors' => false,
      'data'   => compact('posts')
    ];
  }
}

As you can see, we are returning error responses in a specific format, and success responses in a different format.
Soon enough you’ll notice that you’re repeating this over and over again.

Using response macros

Response macros allow you to define a macro that can be called on the response() function.

We will create a new ResponseMacroServiceProvider and define a success and error macros inside the boot function:

<?php

class ResponseMacroServiceProvider extends ServiceProvider
{
  public function boot()
  {
    Response::macro('success', function ($data) {
        return Response::json([
          'errors'  => false,
          'data' => $data,
        ]);
    });

    Response::macro('error', function ($message, $status = 400) {
        return Response::json([
          'errors'  => true,
          'message' => $message,
        ], $status);
    });
  }
}

We also need to add this ServiceProvider to the providers array in config/app.php.
So now we can refactor the previous code:

<?php

class PostsController
{
  public function get()
  {
    try {
      //some code
    }catch (Exception $e){
      return response()->error($e->getMessage);
    }

    $posts = Post::get();
  
    return response()->success(compact('posts'));
  }
}

As you can see, response macros help us remain consistent when returning data from the API. Whether it was a success or an error.
This means your front-end API calls will expect a consistent response.

I will write a new tutorial soon on how you can take it a step further in your front-end by implementing Response Interceptors to handle error responses.


If you like this post, you can share it with your followers.

NDC Oslo - Scaling large Angular apps

I’m excited to announce that I’ll be presenting Scaling Large Angular Apps in NDC Oslo - Norway.

NDC Oslo is one of the biggest developer conferences in Europe. With more than 150 speakers this year, covering over 40 technologies.

Here’s the abstract of my talk:

Scaling beyond the To Do list App of Angular JS. Although Angular JS is a powerful framework, we still need conventions, automation and a variety of tools to make it scale. Especially in a team environment. Learn how to scale your angular apps with simple but effective techniques, endorsed by the Angular community.

This talk will include concepts applicable to both newest angular versions (2 and 1.5)

Are you going to NDC Oslo? If yes, let me know in the comments!


If you like this post, you can share it with your followers.