1. Code
  2. PHP
  3. Laravel

AngularJS and Laravel: Begin Building a CRM

Scroll to top
This post is part of a series called Building a Customer Management App Using AngularJS and Laravel.
AngularJS and Laravel: Finishing Building a CRM

When creating a single-page app we should use some kind of framework to do some of the job for us, so we can focus on the actual functionality. AngularJS fits here perfectly, because features like dynamic dependency injection and bi-directional data binding are just great. Sometimes we also require some kind of server. If you've chosen PHP then Laravel may be your best option, as it's easy to work with and pretty powerful.

Introduction

In this tutorial you will create a simple customer/transaction management system with the ability to add and remove both transactions and customers. This is probably not the kind of thing you make very often, but it shows how to use features of both frameworks.

Before we start you should setup a MySQL database which we will use (Laravel supports many more of them, but this is still the most popular one). You don't need any web server since we will be using PHP's built-in one (but please keep in mind, that this solution is only for the development and should never be used in production - it lacks many features that are required for your app to work properly in public). For that, we will need at least PHP version 5.4.0.

Preparation

The first thing we have to do is to install Laravel. The full process is described on Laravel's website. After that, you should have your project directory created with all of Laravel's files in there. Navigate to that directory in your command line and run this command there:

1
php artisan serve

If all goes OK, you should see that the local development server was started on locahost:8000. Open your browser and navigate there, you should see Laravel's welcome page:

first_runfirst_runfirst_run

Now we can proceed to the actual application.

Migrations and Models

Models in Laravel are just like in any other MVC framework. It's using the Eloquent ORM to ease the work for you - you will probably never need to write an SQL query again (unless you'll want something that Eloquent does not support). Using migrations you can modify the database structure with the ability to rollback changes if something goes wrong. You can read more about migrations in the documentation.

In our app we will use two models:

  • Customer - will hold the customer data
  • Transaction - will hold the information about a transaction

Let's start by creating migrations for them. If you have not done so already, shut down the server we started earlier (Ctrl + C).

Customers

First, invoke this command:

1
php artisan migrate:make create_customers_table

This will create a migration file with a basic structure for you. Now navigate to app/database/migrations. There should be a file with its name starting with a timestamp and ending with "create_customers_table". Laravel automatically created this basic structure for you. The up() method is called when the migration is applied, and down() when it's rolled back.

First call the Schema::create() method. It takes two arguments - the schema's name and a callback function:

1
Schema::create('customers', function ($table) {

The callback is executed when the table is created. The table object is passed as the $table variable and we manipulate the table's structure using it. Let's add an auto-incrementing id field:

1
	$table->increments('id');

Next there will be three string fields for the customer's first name, surname and email:

1
	$table->string('first_name');
2
	$table->string('last_name');
3
	$table->string('email')->unique();

We make the email field unique by calling the unique() method on it.

The last method is for the timestamps:

1
	$table->timestamps();
2
});

This will create two date fields in the schema: created_at and updated_at. These will be used by Eloquent to store the time when the item was created and updated.

Finally, the code should look like this:

1
public function up() {
2
	Schema::create('customers', function ($table) {
3
		$table->increments('id');
4
		$table->string('first_name');
5
		$table->string('last_name');
6
		$table->string('email')->unique();
7
		$table->timestamps();
8
	});
9
}

The down() method is much simpler - it just deletes the schema:

1
public function down() {
2
	Schema::drop('customers');
3
}

Transactions

The code here will be similar to the customers' one. First invoke this command:

1
php artisan migrate:make create_transactions_table

Now locate the appropriate file in the app/database/migrations and open it. Like earlier, start by creating the schema:

1
Schema::create('transactions', function ($table) {

Now add the fields for the id, transaction's name, its cost and the id of the customer that it belongs to:

1
	$table->increments('id');
2
	$table->string('name');
3
	$table->float('amount');
4
	$table->integer('customer_id');

And of course the timestamps:

1
	$table->timestamps();
2
});

The final code should look like this:

1
public function up() {
2
	Schema::create('transactions', function ($table) {
3
		$table->increments('id');
4
		$table->string('name');
5
		$table->float('amount');
6
		$table->integer('customer_id');
7
		$table->timestamps();
8
	});
9
}

And now the down() method:

1
public function down() {
2
	Schema::drop('transactions');
3
}

Database Configuration

Now before you apply the migrations you'll have to configure the connection to your database. Open the app/config/database.php file and go to line 55. Here is the configuration data for MySQL (there are few others in there, for example you could use SQLite or Postgres):

1
'mysql' => array(
2
	'driver'    => 'mysql',                 // database driver, don't touch

3
	'host'      => 'localhost',             // host of the database, usually localhost unless you have your db on some server

4
	'database'  => 'database',              // name of the database you will be using, it must be created earlier

5
	'username'  => 'root',                  // username that the script will use to connect, I strongly advice against using root user for this

6
	'password'  => '',                      // password for the user above, it's better not to use a blank one

7
	'charset'   => 'utf8',                  // encoding of the db

8
	'collation' => 'utf8_unicode_ci',       // db's collation setting

9
	'prefix'    => '',                      // prefix of the database tables, useful if you have multiple scripts using the same database

10
),

After you have filled that in, you are good to go. Make sure you saved the file and invoke this command from your app's main directory (the one with the artisan file in it):

1
php artisan migrate

And thats it. If there were no errors, that means that the tables were created successfully. You can connect to your db using, for example, phpMyAdmin to check manually if you want.

Models

In Laravel, creating a model after you've configured your database using migrations is really quick. Navigate to app/models and delete the example User.php file that is there. Now create two files named Customer.php and Transaction.php.

Let's start with Customer.php. Every model in Laravel has to extend the Eloquent class:

1
class Customer extends Eloquent {

Now we will define a relationship between the customer and their transactions. This is done by defining a public method in the model with the name of the property we would like to have in it (in this case transactions):

1
	public function transactions() {

Now in the body of the function there will be only one line:

1
		return $this->hasMany('Transaction');
2
	}
3
}

This tells Eloquent that it should provide all transactions with customer_id of the customer under a property named transactions.

Now we will do pretty much the same for the transactions, but we will reverse the relationship to make the transaction's owner accessible via the customer property:

1
class Transaction extends Eloquent {
2
	public function customer() {
3
		return $this->belongsTo('Customer');
4
	}
5
}

This is done using the $this->belongsTo() method of the model.

Controllers

Now to actually use the models we have to create controllers for them. Head to the app/controllers directory, delete the HomeController.php only - BaseController.php is important as our controllers will extend it. Now create two files: CustomerController.php and TransactionController.php.

CustomerController

This controller will handle everything related to the customers - adding, removing and showing a list of them. Start by defining the class:

1
class CustomerController extends BaseController {

We will be using Laravel's feature named RESTful controllers. It makes creating routes easier because we only have to define the base URI and Laravel will handle everything for us. This requires you to start your function names with the appropriate HTTP verb and then continue with the subroute name (using camelCase). So for example, if we would have a method named getNames and the base URI would be /customers, then the method will be accessible at /customers/names.

The getIndex(), postIndex(), deleteIndex() etc. methods will be mapped to the default route (in this case /customers).

Now let's define our first route - getting the customer by their id:

1
	public function getIndex() {

Let's get the id from the query parameters (Laravel provides a nice Input class to deal with that, so you don't have to use $_GET, $_POST and $_FILES):

1
		$id = Input::get('id');

And search for the user in the database using that id:

1
		return Customer::find($id);
2
	}

Every method of the controller has to return a value that is a string or has a __toString() method. In this case the Customer model that is returned will be converted to JSON before sending.

Now lets return a list of all users (this will be accessible under /customers/all):

1
	public function getAll() {
2
		return Customer::all();
3
	}

As you can see, we can get all customers using the model's all() method.

Now the longest part, adding a new customer:

1
	public function postIndex() {

First let's check if all information needed was provided. We can do this using the Input::has() method:

1
		if (Input::has('first_name', 'last_name', 'email')) {

Let's put all of the input fields in the $input variable to avoid calling Input::get() over and over. This can be done using Input::all():

1
			$input = Input::all();

Next we will check if any of the inputs are empty. If so, we will return a HTTP 400 Bad Request error with a more verbose message:

1
			if ($input['first_name'] == '' || $input['last_name'] == '' || $input['email'] == '') {
2
				return Response::make('You need to fill all of the input fields', 400);
3
			}

Since we wanted to return a status code other than 200 instead of just returning the message as a string, we used Response::make(), which takes the data to send as the first parameter and the status code as the second. Take a look at the docs if you want to know more about responses.

Now we finally create a new Customer model and feed it with the data provided:

1
			$customer = new Customer;
2
			$customer->first_name = $input['first_name'];
3
			$customer->last_name = $input['last_name'];
4
			$customer->email = $input['email'];

After that we can save the newly created model and respond to the request with it:

1
			$customer->save();
2
			
3
			return $customer;

Here we handle the case if not all of the inputs were provided:

1
		} else {
2
			return Response::make('You need to fill all of the input fields', 400);
3
		}
4
	}

Finally, we also need the ability to remove the customers. This one is really short:

1
	public function deleteIndex() {

We start by getting the id of the customer to delete:

1
		$id = Input::get('id');

Next, we search for and delete the customer:

1
		$customer = Customer::find($id);
2
		$customer->delete();

After that, we respond to the request with the id provided:

1
		
2
		return $id;
3
	}
4
}

Now before the routes can be accessed, we have to hook them. Open the app/routes.php file, delete everything but the comment and add this line at the end of the file:

1
Route::controller('/customers', 'CustomerController');

This will tell Laravel to route all requests at /customers to our CustomerController. Now you can use CURL to play with it. First start the server with php artisan serve and then you can, for example, create a customer:

1
curl -X POST -d "first_name=Jane&last_name=Doe&email=jdoe@gmail.com" http://localhost:8000/customers

Then you can get the list of all customers:

1
curl http://localhost:8000/customers/all

TransactionController

This, like the model is very similar to the CustomerController. First create the class:

1
class TransactionController extends BaseController {

Then let's define the method to get all transactions for a user:

1
	public function getIndex() {
2
		$id = Input::get('id');
3
		return User::find($id)->transactions;
4
	}

As you can see we are using the relationship defined earlier to get the transactions (now recall the query you had to write to achieve the same thing using plain PHP and SQL).

The next thing will be the creation of transactions:

1
	public function postIndex() {

Like earlier, we are checking if all of the required information is provided:

1
		if (Input::has('name', 'amount')) {

If so, assign it to an $input variable:

1
			$input = Input::all();

Check if any of the values provided are empty and if so return an error:

1
			if ($input['name'] == '' || $input['amount'] == '') {
2
				return Response::make('You need to fill all of the input fields', 400);
3
			}

Now create the transaction and supply it with all of the info provided:

1
			$transaction = new Transaction;
2
			$transaction->name = $input['name'];
3
			$transaction->amount = $input['amount'];

Now we need to add it to the appropriate customer. Let's find them by the id provided and add the $transaction to their transactions list:

1
			$id = $input['customer_id'];
2
			User::find($id)->transactions->save($transaction);

This is done using the transactions->save() method provided by Laravel. Now we can respond with the transaction created:

1
			return $transaction;

And handle the case where none or not all of the data was provided:

1
		} else {
2
			return Response::make('You need to fill all of the input fields', 400);
3
		}
4
	}

After that there is also a method to delete the transaction in the same way that we deleted the customer:

1
	public function deleteIndex() {
2
		$id = Input::get('id');
3
		$transaction = Transaction::find($id);
4
		$transaction->delete();
5
		
6
		return $id;
7
	}
8
}

Now just add the route and you can test the controller using CURL:

1
Route::controller('/transactions', 'TransactionController');

Conclusion

Alright, this is the end of the first part - in the second part of this tutorial, we will create the front-end using AngularJS. Feel free to add more features to your app (like editing customers or sorting), in case you did not find the information you were looking for, take a look at Laravel's documentation.

Did you find this post useful?
Want a weekly email summary?
Subscribe below and we’ll send you a weekly email summary of all new Code tutorials. Never miss out on learning about the next big thing.
Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.