This walkthrough should work on a VM described here
Assuming Database configuration is already set
in app/config/database.php or .env file
cd /var/www/dev1.local/laravel
Create Database Migration
In this example I decided to create a Courses table
php artisan make:migration create_courses_table --create=courses
Navigate with SFTP to /var/www/dev1.local/laravel/database/migrations
Edit the created file 2015_11_10_152128_create_courses_table.php and add the required fields.
Adding fields for example, Course name, Classroom, Teacher
$table->string(‘course_name’);
$table->string(‘classroom’);
$table->string(‘teacher’);
Create Models folder in /var/www/dev1.local/laravel/app
mkdir /var/www/dev1.local/laravel/app/Models
Create Course Model
sudo vi mkdir /var/www/dev1.local/laravel/app/Models/Course.php
Seeding the Database
cd /var/www/dev1.local/laravel/database/seeds
sudo vi CoursestTableSeeder.php
vi /var/www/dev1.local/laravel/database/seeds/DatabaseSeeder.php
composer dump-autoload
php artisan clear-compiled
Run php artisan db:seed
Course Controller
php artisan make:controller CourseController
sudo vi /var/www/dev1.local/laravel/app/Http/Controllers/CourseController.php
Implementing the Controller
Add the following uses at the top
use DB;
use Response;
use Input;
use App\Models\Course;
Implementing some of the actions. Index, Store, Show, Delete
public function index()
{
return Response::json(Course::get());
}
public function store()
{
Course::create(array(
‘teacher’ => Input::get(‘teacher’),
‘classroom’ => Input::get(‘classroom’),
‘course_name’ => Input::get(‘course_name’)
));
return Response::json(array(‘success’ => true));
}
public function show($id)
{
$course = Course::find($id);
if(!isset($course)){
return $this->respondNotFound(‘Course does not exist’);
}
return $this->respond([
‘data’ => $this->transform($course)
]);
}
Creating Routes
sudo vi /var/www/dev1.local/laravel/app/Http/routes.php
Add
Route::group([‘prefix’ => ‘/api/v1’], function()
{
Route::resource(‘course’, ‘CourseController’ );
});
save and execute
php artisan route:list
Testing the API
http://dev1.local/index.php/api/v1/courses
or
http://dev1.local/api/v1/courses
Next Post is about Creating Angular based Front-end to consume the above API