Part 1: How to build a Job board with Vue js and the Laravel 5.5 API ?

Commissioning the back end series

Created on: December 20, 2017

Updated on: December 20, 2017

Introduction

Api based applications are used in a plethora of web development services applications and use case scenarios. As users we have become used to using API's in a wide variety of contexts. We use them within forms on bidding sites, they are used to feed vital information from the servers as a means to reduce the amount of data pollution that can occur if the users of your applications have open ended fields.

This effectively means that you have a certain amount of control of the web development services application user interface. In its simplest form an API is a set of requirements that govern how one application can talk to another.

We are going to create our own API in the following tutorial and we will do this in 3 parts. Part 1 is where we will concentrate on the back end, we will create an API using Laravel 5.5, we will create a series of routes that will be consumed by our views. Part 2 will be concerned with setting up our template and the jobs listing. And part 3 will be concerned with wiring up our applications so that the backend and front end talk to each other.

Please note that this 2 part tutorial on setting up an API and front end replaces the Laravel 5.2 API back end / front end tutorial that is currently on medium.com

As with all tutorials we are going to make an assumption here and it is that you already have Laravel Valet installed.

However if you don't, please check out the following link to install it:

https://laravel.com/docs/5.5/valet

To start with go to your command prompt and type the following:


laravel new jobboard

Now that we have created the jobboard directory we need to assign the correct permissions to this directory to ensure we can write to it.

At the command prompt type the following:

cd jobboard

sudo chmod -R 777 vendor storage

Please ensure that you create your database for your application and create a .env file. Within your, .env file make sure that the correct database name and password are added to the environmental variables.

Setting up your model

Create your Job class

At the command prompt type the following:

php artisan make:model Job -m

The job model is used to store all of the attributes that are associated with a job, such as title, type, description etc. We need to specify the fields we declared earlier within the database fields in order to prevent a mass exception violation from occurring.

app

class Job extends Model
{
    protected $fillable = ['reference', 'title', 'type', 'description', 'employer', 'location', 'salary', 'post_date'];
}

Migration

The migration file for the jobs table is located within database / migrations, go in to this folder and add the following fields for our migration.

database/migrations

class CreateJobsTable extends Migration
{

    public function up()
    {
        Schema::create('jobs', function (Blueprint $table) {
            $table->increments('id');
            $table->string('reference');
            $table->string('employer');
            $table->string('title');
            $table->string('location');
            $table->string('salary');
            $table->string('post_date');
            $table->string('type');
            $table->string('description');
            $table->timestamps();
        });
    }

    public function down()
    {
        Schema::dropIfExists('jobs');
    }
}

These are the fields that will appear within each job on our backend.

Lets migrate the database by typing:

php artisan migrate

Model Factories

Now that we have created our jobs table we need to populate this table with data from a Model Factory. Model Factories use the faker library to populate the fields.

At the command prompt type the following:

php artisan make:seeder JobSeeder

Within database/seeds/JobSeeder.php add the following code:

snippet

factory(Job::class, 100)->create();

database/seeds

class DatabaseSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {

    factory(Job::class, 100)->create();

    }
}

The final stage is to set up the model factory so that we can use the faker library to pull that extract the data.

Go to Database/Factories and open up ModelFactory.php.

Add the Job class within there so that it resembles the following:

database/factories/ModelFactory.php

$factory->define(App\User::class, function (Faker $faker) {
    static $password;

    return [
        'name' => $faker->name,
        'email' => $faker->unique()->safeEmail,
        'password' => $password ?: $password = bcrypt('secret'),
        'remember_token' => str_random(10),
    ];
});

    $factory->define(App\Job::class, function (Faker $faker) {
        return [
            'reference' => $faker->domainWord,
            'employer' => $faker->company,
            'title' => $faker->jobTitle,
            'location' => $faker->city,
            'salary' => $faker->numberBetween($min = 1000, $max = 9000),
            'post_date' => $faker->dateTimeBetween($startDate = '-30 years',
                $endDate = 'now', $timezone = date_default_timezone_get()),
            'type' => $faker->jobTitle,
            'description' => $faker->sentence
        ];
    });

Let’s run our seeder at the command prompt run:

php artisan db:seed

The Controllers

We need to create a controller for our application and we will be using a RESTFUL controller as best practice.

At the command prompt type the following:

php artisan make:controller Api/JobsController

This will create the JobsController underneath the app\Http\Controllers\Api directory.

Go to the routes directory and edit the web.php file and add the following:

Web.php

Route::group(['prefix' => 'api'], function () {

    Route::get('jobs', 'Api\[email protected]');

    Route::get('jobs/{job}', 'Api\[email protected]');

    Route::post('jobs','Api\[email protected]');

    Route::patch('jobs/{jobs}','Api\[email protected]');

    Route::delete('jobs/{job}', 'Api\[email protected]');
});

Route model binding on routes file

Notice that we have used implicit model binding to add the model (in this case Job) in to our routes file using the RESTFUL Api.

We now need to create a series of methods on the JobsController to ensure that the respective views will receive the correct data.

Firstly we are going to add the index method to the JobsController this will return a listing of all jobs and these will be returned to the view.

Http\Controllers\ApiJobsController.php

class JobsController extends Controller { /**

  • Display a listing of the resource.
  • @return \Illuminate\Http\Response */

    public function index() { return Job::all(); } }


Next we will add a show method this will search for a job using its ID and return it to the view. And we will add a store method this will create a new job using the Request and the view will be returned.

Http\Controllers\ApiJobsController.php

class JobsController extends Controller { /**

  • Display a listing of the resource.
  • @return \Illuminate\Http\Response */

    public function index() { return Job::all();

    }

    /**

  • Display the specified Job.
  • @param int $id
  • @return \Illuminate\Http\Response */

    public function show(Job $job) { return $job;

    }

    /**

  • Store a newly created Job in storage.
  • @param \Illuminate\Http\Request $request
  • @return \Illuminate\Http\Response */

    public function store(Request $request) { $job = Job::create($request->all());

    return response()->json($job, 201);

    } }


We will add the update and destroy methods to the JobsController. 

The update method searches for the Job and updates the job using the data from the request. 
public function update(Job $job, Request $request)
{
    $job->update($request->all());

    return response()->json($job, 200);

}

Whilst the delete method searches for the job and it deletes the job and returns a boolean value (true or false) to indicate if it was successful or not using the JSON format.
public function delete(Job $job)
{
    $job->delete();

    return response()->json(null, 204);
}

Please add these methods in to our JobsController and ensure that your controller looks like the following:

class JobsController extends Controller { /**

  • Display a listing of the resource.
  • @return \Illuminate\Http\Response
  • /

    public function index()
    {
    return Job::all();
    }

    /**

  • Display the specified Job.
  • @param Job $job
  • @return \Illuminate\Http\Response
  • @internal param Product|int $product */

    public function show(Job $job)
    {
    return $job;
    }

    /**

  • Store a newly created Job in storage.
  • @param \Illuminate\Http\Request $request
  • @return \Illuminate\Http\Response */

    public function store(Request $request)
    {
    $job = Job::create($request->all());
    
    return response()->json($job, 201);
    }

    /**

  • Update the job.
  • @param Job $job
  • @param Request $request
  • @return mixed
  • @internal param $id */

    public function update(Job $job, Request $request)
    {
    $job->update($request->all());
    
    return response()->json($job, 200);
    }

    /**

  • Delete the job
  • @param Job $job
  • @return mixed
  • @internal param $id */

    public function delete(Job $job)
    {
    
    $job->delete();
    
    return response()->json(null, 204);
    }
    
    }

This concludes part 1 of our tutorial and we built the backend using the RESTFUL api in a series of method.

Let us know your experiences of creating an API for use with a JavaScript front end in the discus comments listed below.

Stay tuned for part 2 where we will create a front-end using Vuejs and we will render the job listings and for further tips and tricks click www.ormrepo.co.uk/blogs.

The link also provides information about the web development services we offer.