Skip to content

Build REST apis with Laravel 4.2

Last updated on February 17, 2018

Create a brand new Laravel Project with below command

$ composer create-project laravel/laravel todo 4.2 --prefer-dist

Configure Your Database

Open config/database.php file and update it with your database details as shown below

	'mysql' => array(
			'driver'    => 'mysql',
			'host'      => 'localhost',
			'database'  => 'laravel42',
			'username'  => 'root',
			'password'  => '',
			'charset'   => 'utf8',
			'collation' => 'utf8_unicode_ci',
			'prefix'    => '',
		),

Create Migration files and tables

We gonna have users and areas tables, so lets create migration file with below commands, which will create creates new files in your app/database/migration directory

php artisan migrate:make create_users_table --table=users --create
php artisan migrate:make create_areas_table --table=areas --create

Let’s updated your migration file’s up methods with below code blocks.

2017_10_04_085548_create_users_table.php

	public function up()
	{
		Schema::create('users', function(Blueprint $table)
		{
			$table->increments('id');
			$table->string('first_name');
			$table->string('last_name');
			$table->string('email')->unique();
			$table->string('password');
			$table->timestamps();
		});
	}
2017_10_04_085555_create_areas_table.php

	public function up()
	{
               Schema::create('areas', function(Blueprint $table)
		{
			$table->increments('id');
			$table->string('name');
			$table->integer('created_by');
			$table->integer('updated_by');
			$table->timestamps();
		});
	}

Now run above migrations with below command, it will create your tables as per migration file within the specified database(app/config/database.php).

php arisan migrate 

Create Models

Let’s create user and area models as shown below.
create User.php file in app/modes directory with below code


create Area.php file in app/modes directory with below code

hasOne('User','id','created_by');
	 }

	 public function updatedBy() {
		return $this->hasOne('User','id','updated_by');
	 }
}

Create Controller

Create AreaController.php file in your app/controller directory with below code

get();
		
		$results = [];
		foreach($areas as $area) {
			$results[] = $this->formateArea($area);
		}

		return $results;
	}

	/**
	 * Store a newly created resource in storage.
	 *
	 * @return Response
	 */
	public function store()
	{
		$area = new Area;
		$area->name = array_get($input,'name');
		//$area->created_by = Auth::user()->id;
		//$area->updated_by = Auth::user()->id;
		 
		$area->save();
	 
		return Response::json([
			'error' => false,
			'area' => $area->toArray()],
			200
		);
	}


	/**
	 * Display the specified resource.
	 *
	 * @param  int  $id
	 * @return Response
	 */
	public function show($id)
	{
	
		$area = Area::with(['createdBy','updatedBy'])
		 ->where('id', $id)
		->take(1)
		->firstOrFail();
 
		return Response::json(array(
			'error' => false,
			'area' => $this->formateArea($area)),
			200
		);
	}

	/**
	 * Update the specified resource in storage.
	 *
	 * @param  int  $id
	 * @return Response
	 */
	public function update($id)
	{

		$input = Input::Only('name');

		$validator = Validator::make(
			array(
				'name' => array_get($input,'name'),
			),
			array(
				'name' => 'required'
			)
		);

		if ($validator->fails())
		{
			return Response::json([
				'error' => true,
				'messages' => $validator->messages()],
				400
			);
		}

		$area = Area::find($id);

		if(!$area) {
			return Response::json(array(
				'error' => true,
				'message' => 'Area not found'),
				404
			);
		}

		
		if($name = array_get($input,'name')) {
			$area->name = $name;
		}
		
	//	$area->updated_by = Auth::user()->id;

		$area->save();
	
		return Response::json(array(
			'error' => false,
			'message' => 'Area updated'),
			200
		);
	}


	/**
	 * Remove the specified resource from storage.
	 *
	 * @param  int  $id
	 * @return Response
	 */
	public function destroy($id)
	{
		$area = Area::find($id)->delete();
				
		return Response::json([
			'error' => false,
			'message' => 'Area deleted'],
			 200
			);
	}

	protected function formateArea($area) {

		return [
			'id' => $area->id,
			'name' => $area->name,
			'created_by' => [
				'first_name' => $area->createdBy->first_name,
				'last_name' => $area->createdBy->last_name,
				'email' => $area->createdBy->email,
			],
			'updated_by' => [
				'first_name' => $area->createdBy->first_name,
				'last_name' => $area->createdBy->last_name,
				'email' => $area->createdBy->email,
			],
			'created_at'  => $area->created_at,
			'updated_at' => $area->updated_at
		];
	}


}

Define route

Open your app/routes.php file and add following route definition.

Route::resource('/areas','AreaController');

Now you can access following routes -
GET - http://localhost:8000/areas - it will return all the areas
POST - http://localhost:8000/areas - you can create an area
PUT - http://localhost:8000/areas/1 - you can update 1st area, here 1 is the primary key for the areas table.
DELETE - http://localhost:8000/areas/1 - you can DELETE 1st area, here 1 is the primary key for the areas table.

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments