Laravel and PostgreSQL Web App Part 7

Introduction

Throughout this multi-part tutorial series, we’ve been walking you through all the steps needed to create a Laravel and PostgreSQL web app. We’ve gotten through a fair amount of the project so far, but we have several important tasks left to accomplish. In this article, we’ll pick up where we left off and show you how to delete a selected record in the PostgreSQL database.

Prerequisites

Before you tackle the steps listed in this article, be sure you’ve completed the work outlined in the previous installments of this series.

Laravel and PostgreSQL Web App Part 1

Laravel and PostgreSQL Web App Part 2

Laravel and PostgreSQL Web App Part 3

Laravel and PostgreSQL Web App Part 4

Laravel and PostgreSQL Web App Part 5

Laravel and PostgreSQL Web App Part 6

How to DELETE a record in PostgreSQL using Laravel

In the previous article, we showed how to UPDATE a certain PostgreSQL record. Now we’ll demonstrate how to perform a DELETE operation on a record in the database using axios.

First, we need to install axios using npm:

npm install --save axios

In our next step, we’ll be working with a Javascript assets file, so we’ll need to access the following directory: ‘resources-assets-js’. We’re going to create a file named custom.js in this directory. We’ll use the following code:

let axios = require("axios");

//event delegation
$("body").on("click", ".delete-projects", function() {
  let id = $(this).data("id");

  // axios will send a delete request with this URL
  axios
    .delete("/projects/" + id)
    .then(function() {
      window.location.reload();
    })
    .catch(function(error) {
      console.log(error);
    });
});

The code shown above uses a construct known as an event delegation. This means that a function will be run when the button having a class of delete-projects is clicked.

We’ll take the value of the id from the data attribute and assign it to an id variable.

Next, we’ll create our delete request using axios, and we’ll want to specify '/projects/'+id as the location.

Finally, we’ll reload the page after the record is deleted.

Once we add this code to the file, we’ll need to include this file in our app.js by simply appending the following line: require('./custom');.

After this, we’ll need to compile our application via command line. We’ll navigate to our project directory and run the command shown below:

npm run dev

We need to modify our delete button in order to send the id of the record that we want to remove from our database. We’ll use the following code to make this work:

<td> <button data-id="{{$project->id}}" type="button" class="delete-projects btn btn-danger" name="button"><span class="fa fa-trash"></span>Delete</button>

We’ll need to intercept the request from the axios.delete function, which uses the following URL '/projects/'+id. After that, we’ll need to create a route for it inside the web.ph file. We’ll use the following code:

Route::delete('/projects/{id}', 'ProjectsController@destroy');

We’ll also create a function named destroy inside our controller ProjectsController.php file. The code shown below can be used to create the function:

 public function destroy($id)
    {
        $project = Project::find($id);
        $project->delete();

        return;
    }

In the code above, we find the project using the id, then we assign the details to the variable $projecg. From there, we perform the delete function with just a single line of code: $project->delete();. We don’t return anything as we are not going to navigate away from the homepage.

We can test our changes now and check out our Laravel and PostgreSQL web app:

Conclusion

As we’ve worked through our multi-part tutorial series, we’ve made a lot of progress with our Laravel and PostgreSQL web app. In this installment, we continued where we left off in the previous article, showing you how to write the code needed to delete a record from the database. With these instructions to guide you, you’ll be able to create your own web application using PostgreSQL and the Laravel framework.

The Code

We’ve added code to multiple files in this tutorial. Shown below is all the code we used to modify various articles:

The app.js

/**
 * First we will load all of this project's JavaScript dependencies which
 * includes Vue and other libraries. It is a great starting point when
 * building robust, powerful web applications using Vue and Laravel.
 */

require("./custom");
require("./bootstrap");

window.Vue = require("vue");

/**
 * The following block of code may be used to automatically register your
 * Vue components. It will recursively scan this directory for the Vue
 * components and automatically register them with their "basename".
 *
 * Eg. ./components/ExampleComponent.vue -> <example-component></example-component>
 */


// const files = require.context('./', true, /\.vue$/i)
// files.keys().map(key => Vue.component(key.split('/').pop().split('.')[0], files(key).default))

Vue.component(
  "example-component",
  require("./components/ExampleComponent.vue").default
);

/**
 * Next, we will create a fresh Vue application instance and attach it to
 * the page. Then, you may begin adding components to this application
 * or customize the JavaScript scaffolding to fit your unique needs.
 */


const app = new Vue({
  el: "#app"
});

The Homepage home.blade.php

<tbody>
@foreach($projects as $project)
    <tr>
    <th scope="row"> {{$project->id}}</th>
    <td> {{$project->name}}</td>
    <td> {{$project->description}}</td>
    <td> <button data-id="{{$project->id}}" type="button" class="delete-projects btn btn-danger" name="button"><span class="fa fa-trash"></span>Delete</button>

    <td> <button type="button"
    data-project_name="{{$project->name}}"
    data-description="{{$project->description}}"
    data-project_id="{{$project->id}}"
    data-toggle="modal"
    data-target="#editModal" class="btn btn-primary" name="button" ><span class="fa fa-edit"  ></span>Edit</button>
    </td>
    <td><button onclick="myFunction()">Try it</button></td>
    </tr>
    @endforeach
</tbody>

The custom.js

let axios = require("axios");

//even delegation
$("body").on("click", ".delete-projects", function() {
  let id = $(this).data("id");

  // axios will send a delete request with this URL
  axios
    .delete("/projects/" + id)
    .then(function() {
      window.location.reload();
    })
    .catch(function(error) {
      console.log(error);
    });
});

The web.php file

<?php

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/


Route::get('/', function () {
    return view('welcome');
});

Auth::routes();



Route::get('/home', 'ProjectsController@index')->name('home');
Route::post('store',['as' => 'projects.store', 'uses' => 'ProjectsController@store']);
Route::post('update',['as' => 'project.update', 'uses' => 'ProjectsController@update'] );
Route::delete('/projects/{id}', 'ProjectsController@destroy');

The ProjectsController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Project;
class ProjectsController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth');
    }


    public function index()
    {
        $project = Project::where('user_id', auth()->user()->id)->get();
        return view('home')->with('projects', $project);
    }

    public function store(Request $request){
        // validation
        $this->validate($request,[
            'project_name' => 'required',
            'description'  => 'required'
        ]);


        // create project
        $project = new Project;
        $project->name = $request->input('project_name');
        $project->description = $request->input('description');
        $project->user_id = auth()->user()->id;

        $project->save();

        return redirect('/home')->with('success', 'Project Added');
    }

    public function update(Request $request){

        $project = array(

            'name' => $request->project_name,
            'description' => $request->description,
            'user_id' => auth()->user()->id
        );

        Project::findOrFail($request->input('project_id'))->update($project);


        return redirect('/home')->with('success', 'Project Updated');

    }

    public function destroy($id)
    {
        $project = Project::find($id);
        $project->delete();

        return;
    }
}

Pilot the ObjectRocket Platform Free!

Try Fully-Managed CockroachDB, Elasticsearch, MongoDB, PostgreSQL (Beta) or Redis.

Get Started

Keep in the know!

Subscribe to our emails and we’ll let you know what’s going on at ObjectRocket. We hate spam and make it easy to unsubscribe.