
How to create `to-do` app using AngularJS and Laravel 5
In this tutorial, I’m going to demonstrate making a Single Page Application using Laravel php framework and AngularJS 1. So I got interested in exploring Laravel in the past weeks and I thought of sharing this with you once I get this to work.
While I’ve read lots of tutorial to make this work, I felt that most samples are using Laravel 4 so most of the tutorials were a little bit outdated. I had to research the similar syntax from 4 to 5 until it worked. It wasn’t easy.
Fortunately, in this to-do app, I used an updated Laravel 5 and got this to work. Most of the syntax used in Laravel 4 won’t work with Laravel 5 so I had a hard time in making this work. Anyway, what matters is I got it to work. Yeeeey!!
Before that, you can download working source code here: https://github.com/reciosonny/angular-laravel-todo-app
What you’ll expect in this tutorial
At the end of the session, you’re going to learn the following:
- Creating RESTful services using Laravel
- Using Angular to consume REST API from Laravel
- Mix Angular and Laravel together
Prerequisites
In order to make this work, you must have the following in your local machine:
- php
- Composer
- Laravel 5 installer(you can get this via composer)
- mysql
Assumptions
This article assumes that you have prior knowledge of the following technologies(at least basic grasp):
- Laravel 5
- Angular 1.5
So, I will not cover as much explanations as possible in these things. What I will emphasize more is how we tie these technologies together up to make a robust and maintainable Single Page Application.
Okay! Let’s get started!!
Getting Started
Let’s think of a way that we can use AngularJS in this setup. To make full use of Angular, we’re gonna create RESTful services using Laravel. So we won’t get in touch deeper with Laravel’s blade engine. If you’re expecting to use blade engine and utilize Laravel at its fullest, look elsewhere.
To create RESTful services, let us prepare our laravel app first.
Preparing Laravel
So we need to do a couple of things before we get a running laravel app. Don’t worry, it’s pretty easy and for the most part laravel will bootstrap everything for you.
To start, kindly create a laravel app by typing this command(in your command line):
laravel new angular-laravel-todo
This creates a new laravel project with the folder name of “angular-laravel-todo”.
Getting database ready
Before we get started, let’s setup our database first. We just need the following columns in our todo table:
- TodoName -> string
- IsDone -> bit
For the sake of simplicity and demonstrating of angular integration to laravel, we’ll make database constructs as minimal as possible. And no middleware(I’m going to make another tutorial for that though). For now, this is the goal of the article.
First, we needed to create a database migration, so let’s kindly type the following:
php artisan make:migration create_todo_table
This creates a migration for TodoList table.
Now, paste the following code to the migration file you’ve just generated:
/**
* Run the migrations.
* @return void
*/
public function up()
{
Schema::create(‘todolists’, function (Blueprint $table) {
$table->increments(‘id’);
$table->string(‘TodoName’);
$table->boolean(‘IsDone’);
$table->integer(‘OrderNum’);
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop(‘todolists’);
}
Finally, type the following in your command line:
php artisan migrate
This converts your migrations we’ve just created as a table in mysql.
Last but not the least, we needed to create a database model for our application.
php artisan make:model Todolist
This creates a database model for you.
By default, Laravel will use Eloquent ORM models to model our database application and persist our data. By simply mastering the basics of artisan commands, you can create eloquent as fast as you need.
Note: make sure you’ve changed the variables from .env file to make migrations work smoothly.
Creating a controller
Now that we’re done explaining the artisan command, let’s start by creating a controller for our Todo table.
Type this command in your command line inside laravel folder app you’ve just made:
php artisan make:controller TodoController
This command creates a controller. Here we will put all of our RESTful services to communicate with Angular.
Now, paste the following code inside your controller:
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
return Todolist::all();
}
public function getAllActiveTodos()
{
return Todolist::where(‘IsDone’, false)->get();
}
public function getAllCompletedTodos()
{
return Todolist::where(‘IsDone’, true)->get();
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$todo = new Todolist($request->all());
// $todo->TodoName = ‘test’;
// $todo->UserId = 1; //assign this to user later
$todo->save();
return Response::json($todo);
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
//
return Todolist::find($id);
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
$todo = Todolist::find($id);
$todo->TodoName = $request->TodoName;
$todo->IsDone = $request->IsDone;
$todo->save();
return Response::json($todo);
}
Now we needed to setup a router to make use of your controller.
Configuring a router to enable RESTful services
We use routers to point url requests to its appropriate controllers. But in laravel, we can still execute an action by directing it to the router itself, something that I find more flexible and accessible than ASP.net MVC.
Well anyway, kindly paste the following source code into your router(routes.php):
Route::auth();
Route::get(‘/home’, ‘HomeController@index’);
Route::get(‘/’, function () {
return view(‘index’);
});
Route::group([‘prefix’ => ‘api/v1’], function() {
Route::get(‘todos/active’, ‘TodoController@getAllActiveTodos’);
Route::get(‘todos/completed’, ‘TodoController@getAllCompletedTodos’);
Route::resource(‘todos’, ‘TodoController’);
});
Noticed the Route::group in the code. This groups our controller which gives us a better control in our routing. We could also apply additional parameters across different routes when grouped under it like we could automatically apply common route prefix across different routes.
In this case, we wanted to use the name ‘api/v1’ as our prefix to let consumers of the api know this is a RESTful service.
Before we setup AngularJS
This is just optional, but we can relocate and reroute all our views in public folder. This is a good practice when we’re using Single Page Application such as Angular into our web app and unify all files in public section, including views.
By default, our views were located in resource folder. So when we call the view() method, it points to resource/views folder by default.
We could simply change the pointer to config/view.php.
Kindly replace the path code with the following:
realpath(base_path(‘public/views’)), //put all views to public for AngularJS use
This now ensures that we could use and put all of our views within the public/views folder instead of resource/views.
Setting up AngularJS
Now that we took care of all setups in Laravel to implement a simple CRUD operation in REST format, all we need to do for final step is to setup our angular to make everything work.
Public folder structure
We need to setup the folder structure first. I structured this app using the following:
Public/
|
| — -Content/
| — -js/
— — — libraries/
— — — services/
| — -Views/
Creating angular service for RESTful calls
We’re going to use angular factory to further isolate our REST API calls. This also makes our API reusable in the long run so that our controllers won’t be cluttered with a lot of $http() calls. It’s a great way, cleaner and pretty straightforward.
Create a file todoService.js inside public/js/services folder and copy the following code:
We’ll inject this later in our main module to become usable.
Creating angular routes
Angular routes are a great way to utilize Angular’s architecture to implement Single Page Applications. Not only that, it also organizes our views further and assign an appropriate controller in that view without injecting ng-controller in each dom scope which we would like to use. In this sample, we only used the default routing system of angular instead of using Angular UI Route.
Although it’s not necessary for this tutorial and we could just simply inject the controller directly in dom by simply using ng-controller directive, I feel like separating it further to avoid clutter and fully utilize Angular’s functionality.
Create a file named mainRoutes.js inside public/js folder and copy the following code:
Creating controller and main module
Now, we’re going to create a controller and main module to start consuming REST API within Angular and use the service we’ve made in Angular.
Create a file named mainApp.js inside public/js folder and copy the following code:
I intentionally wanted to separate the controller code into another js file and inject it but to simplify everything I just simply put it in the same main js file where we’re going to inject all other dependencies we’ve created in Angular.
Create partial view template
Since we’ve used routing in our angular app, we needed to create a partial view template to make the route work.
Create a file main.php inside public/views folder and paste the following code:
We can just simply inject the ng-controller in the route file we’ve created earlier and we let it do the work instead of injecting it inside dom. I believe this is a cleaner approach than using ng-controller.
And Finally
Create index.php inside public/views folder and make sure you put this in your body:
<ng-view></ng-view>
This directive communicates with the routing we’ve created for Angular and display the default partial template for default route.
Conclusion
Whew! Finally we’re done. This looks like a lot of work from the bird’s eye view. I promise you I made this as simple as possible. But I’m glad we’re able to finish a simple demonstration of simple todo app using laravel and AngularJS. Happy coding!
Let me know if you encountered some errors or bugs. Or share your thoughts in the comment section!