Create a Laravel Vue Single Page App in Under an Hour

 

Create a Laravel Vue Single Page App in Under an Hour




Laravel Vue single-page app is becoming the most popular choice for developing PHP projects. One important reason for this popularity is Vue JS. Vue gives an expressive API for building strong JavaScript applications utilizing components. As with CSS, we may utilize Laravel Blend to effectively compile JavaScript components into a single, browser-ready JavaScript file.

The combination of Laravel Vue JS results in fast, secure, and impressive applications that need minimum time to go from ideation to final code review. The support for Vue.js means that Laravel developers could use Vue components easily within their apps without wasting time in writing integrations for the components. To demonstrate the support, I decided to create a single-page app in Laravel with a Vue.js-powered frontend.

Why You Should Use Vue with Laravel

VueJS is simple and less opinionated than other frameworks. It has a CLI project generator which makes it easy to build a project prototype having a temporary structure. Its CLI executes an upgradeable runtime dependency which can be extended using a plugin.
Vue offers a variety of default options for different tasks and also provides a pre-established conventional environment for building enterprise-level applications. The framework’s syntax is completely harnessed from the JavaScript expression.
Nowadays, there is a big fuss over why we should use VueJS with Laravel. The question that needs to be asked is what does Vue have to offer and how will it comply with our functional needs?
Here are some of the important features that make VueJS a pretty handy tool to use with Laravel:

Front-end is Everything

Today, the whole internet is event-driven, and these events are being updated on the screen displayed to the user. So, for the user to be up-to-date, there is no need to refresh their page again and again, thanks to JavaScript.

Reactiveness of Vue

A highly interactive frontend can be built using VueJS, in which the display of the user is event-driven and all the activity around him is updated quickly. The framework provides an amazing experience for the users, as it can trigger UI changes dynamically and can couple them very nicely with Laravel.

Single Page WebApp

In remote countries where accessing the internet sometimes becomes difficult, a single page application gives ease to load the URL if it is cached earlier. It allows users to access the application multiple times, as it is saved earlier in the caches requiring less time to load in the browser.

Easy to Use

Vue is really easy to get started with as it works with simple concept of JavaScript. It allows you to build non-trivial applications within minutes, as it is pretty straightforward and easy to understand. Moreover, if your template is built on HTML, it automatically becomes valid for VueJS as it requires no additional scripting to change the existing structure. 

Prerequisites

For the purpose of this Laravel Vue JS tutorial, I assume that you have a Laravel application installed on a web server.

Install Node.js with NPM

The first step is the installation of Node.js with NPM.

For this first install Node.js. Next go to the project’s folder and type the following command in the terminal:

  1. npm init
  2. npm install

This command will install all the JavaScript dependencies for VueJS. In addition, the command will also install laravel-mix, an API for defining webpack.

Configure the Database

Now setup the MySQL database and configure it in Laravel.

In the project root, you will find the .env and config/database.php files. Add the database credentials (username, DB name, and password) to setup the database and allow the Laravel Single page app to access it.

Create the Migrations

In the third step, open the terminal and go to the root of the newly created Laravel project and generate a new migration to create task table:

  1. cd /path-to-project/project-name
  2. php artisan make:migration create_tasks_table --create=tasks

Next , open the migration file located in the database/migration2 folder and replace the up() function with the following code:

  1. public function up()
  2. {
  3. Schema::create('tasks', function (Blueprint $table) {
  4. $table->increments('id');
  5. $table->string('name');
  6. $table->unsignedInteger('user_id');
  7. $table->text('description');
  8. $table->timestamps();
  9. });
  10. }

Next , In the app/Providers/AppServiceProvider.php file, the boot method sets a default string length:

  1. use Illuminate\Support\Facades\Schema;
  2. public function boot()
  3. {
  4. Schema::defaultStringLength(191);
  5. }

Run the Migration

Create the tables in the database by using the following command:

  1. Php artisan migrate

Setup User Authentication

Laravel provide default user authentication in which you can register users who can then login through the provided login system. This login system also provides Laravel CRSF authentication token to further strengthen the security of the application against malicious exploits. Use the following command to set up user authentication in the Laravel Vue SPA:

  1. php artisan make:auth

Create Task Model and Task Controller

Create task model because I will handle database operations through Laravel Eloquent. I also need a controller to handle user requests such as create, read, update and delete operations.

Use the following command to create the model and the controller:

  1. php artisan make:model Task -r

Next open the Task Model which in app/Task.php and controller at /app/Http/Controllers/TaskController.php. Update the model code with the following code.

  1. <?php
  2. namespace App;
  3. use Illuminate\Database\Eloquent\Model;
  4. use Illuminate\Contracts\Validation\Validator;
  5. class Task extends Model
  6. {
  7. protected $fillable = [
  8. 'name',
  9. 'user_id',
  10. 'description',
  11. ];
  12. }

The Code for Controller

Next, update the controller file with the following code.

  1. <?php
  2. namespace App\Http\Controllers;
  3. use App\Task;
  4. use Illuminate\Http\Request;
  5. use Illuminate\Support\Facades\Auth;
  6. class TaskController extends Controller
  7. {
  8. /**
  9. * Display a listing of the resource.
  10. *
  11. * @return \Illuminate\Http\Response
  12. */
  13. public function index()
  14. {
  15. $tasks = Task::where(['user_id' => Auth::user()->id])->get();
  16. return response()->json([
  17. 'tasks' => $tasks,
  18. ], 200);
  19. }
  20. /**
  21. * Show the form for creating a new resource.
  22. *
  23. * @return \Illuminate\Http\Response
  24. */
  25. public function create()
  26. {
  27. //
  28. }
  29. /**
  30. * Store a newly created resource in storage.
  31. *
  32. * @param \Illuminate\Http\Request $request
  33. * @return \Illuminate\Http\Response
  34. */
  35. public function store(Request $request)
  36. {
  37. }
  38. /**
  39. * Display the specified resource.
  40. *
  41. * @param \App\Task $task
  42. * @return \Illuminate\Http\Response
  43. */
  44. public function show(Task $task)
  45. {
  46. //
  47. }
  48. /**
  49. * Show the form for editing the specified resource.
  50. *
  51. * @param \App\Task $task
  52. * @return \Illuminate\Http\Response
  53. */
  54. public function edit(Task $task)
  55. {
  56. //
  57. }
  58. /**
  59. * Update the specified resource in storage.
  60. *
  61. * @param \Illuminate\Http\Request $request
  62. * @param \App\Task $task
  63. * @return \Illuminate\Http\Response
  64. */
  65. public function update(Request $request, Task $task)
  66. {
  67. }
  68. /**
  69. * Remove the specified resource from storage.
  70. *
  71. * @param \App\Task $task
  72. * @return \Illuminate\Http\Response
  73. */
  74. public function destroy(Task $task)
  75. {
  76. }
  77. }

Middleware

To setup middleware for Laravel SPA, add the following code to the Task Controller.

  1. public function __construct()
  2. {
  3. $this->middleware('auth');
  4. }

Create the Method

In the store() method of Task Controller, update the following code to add data into database.

  1. $this->validate($request, [
  2. 'name' => 'required',
  3. 'description' => 'required',
  4. ]);
  5. $task = Task::create([
  6. 'name' => request('name'),
  7. 'description' => request('description'),
  8. 'user_id' => Auth::user()->id
  9. ]);
  10. return response()->json([
  11. 'task' => $task,
  12. 'message' => 'Success'
  13. ], 200);

Update Method

In Update() method of Task Controller, update the following code to edit database data. database.

  1. $this->validate($request, [
  2. 'name' => 'required|max:255',
  3. 'description' => 'required',
  4. ]);
  5. $task->name = request('name');
  6. $task->description = request('description');
  7. $task->save();
  8. return response()->json([
  9. 'message' => 'Task updated successfully!'
  10. ], 200);

Delete Method

In the Destroy() method of Task Controller,  the following code will delete data from the database.

  1. $task->delete();
  2. return response()->json([
  3. 'message' => 'Task deleted successfully!'
  4. ], 200);

Route Set up in Laravel SPA

Route sets the application URL and the controller method for the URL. Routes are located in route/web.php and contains the following code:

  1. Route::get('/home', 'HomeController@index')->name('home');
  2. Route::resource('/task', 'TaskController');

Create Vue.js Components

Create a new file for Task component inside /resources/assets/js/components/ folder named Task.vue and add following sample code:

  1. Task.vue:
  2. <template>
  3. <div class="container">
  4. <div class="row">
  5. <div class="col-md-12">
  6. <div class="panel panel-default">
  7. <div class="panel-heading">My Assigments</div>
  8. <div class="panel-body">
  9. </div>
  10. </div>
  11. </div>
  12. </div>
  13. </div>
  14. </template>
  15. <script>
  16. export default {
  17. mounted() {
  18. }
  19. }
  20. </script>

The component is ready for registration. Open app.js file from /resources/assets/js/app.js and add the following line after example component registration line:

  1. app.js:
  2. Vue.component('task', require('./components/Task.vue'));

Compile Assets

Use the following command to compile the newly added code as a Vue.js component. This will also register component:

  1. npm run dev

Calling in the View

Now open home.blade.php located in /resources/views/ and update it as follows:

  1. @extends('layouts.app')
  2. @section('content')
  3. <task></task>
  4. @endsection

Create Update & Delete in Task.vue

The Task component is located inside /resources/assets/js/components/ and is named Task.vue. Open this file and update the code:

  1. <template>
  2. <div class="container">
  3. <div class="row">
  4. <div class="col-md-12">
  5. <div class="panel panel-default">
  6. <div class="panel-heading">
  7. <h3><span class="glyphicon glyphicon-dashboard"></span> Assignment Dashboard </h3> <br>
  8. <button @click="initAddTask()" class="btn btn-success " style="padding:5px">
  9. Add New Assignment
  10. </button>
  11. </div>
  12. <div class="panel-body">
  13. <table class="table table-bordered table-striped table-responsive" v-if="tasks.length > 0">
  14. <tbody>
  15. <tr>
  16. <th>
  17. No.
  18. </th>
  19. <th>
  20. Name
  21. </th>
  22. <th>
  23. Description
  24. </th>
  25. <th>
  26. Action
  27. </th>
  28. </tr>
  29. <tr v-for="(task, index) in tasks">
  30. <td>{{ index + 1 }}</td>
  31. <td>
  32. {{ task.name }}
  33. </td>
  34. <td>
  35. {{ task.description }}
  36. </td>
  37. <td>
  38. <button @click="initUpdate(index)" class="btn btn-success btn-xs" style="padding:8px"><span class="glyphicon glyphicon-edit"></span></button>
  39. <button @click="deleteTask(index)" class="btn btn-danger btn-xs" style="padding:8px"><span class="glyphicon glyphicon-trash"></span></button>
  40. </td>
  41. </tr>
  42. </tbody>
  43. </table>
  44. </div>
  45. </div>
  46. </div>
  47. </div>
  48. <div class="modal fade" tabindex="-1" role="dialog" id="add_task_model">
  49. <div class="modal-dialog" role="document">
  50. <div class="modal-content">
  51. <div class="modal-header">
  52. <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
  53. aria-hidden="true">&times;</span></button>
  54. <h4 class="modal-title">Add New Task</h4>
  55. </div>
  56. <div class="modal-body">
  57. <div class="alert alert-danger" v-if="errors.length > 0">
  58. <ul>
  59. <li v-for="error in errors">{{ error }}</li>
  60. </ul>
  61. </div>
  62. <div class="form-group">
  63. <label for="names">Name:</label>
  64. <input type="text" name="name" id="name" placeholder="Task Name" class="form-control"
  65. v-model="task.name">
  66. </div>
  67. <div class="form-group">
  68. <label for="description">Description:</label>
  69. <textarea name="description" id="description" cols="30" rows="5" class="form-control"
  70. placeholder="Task Description" v-model="task.description"></textarea>
  71. </div>
  72. </div>
  73. <div class="modal-footer">
  74. <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
  75. <button type="button" @click="createTask" class="btn btn-primary">Submit</button>
  76. </div>
  77. </div><!-- /.modal-content -->
  78. </div><!-- /.modal-dialog -->
  79. </div><!-- /.modal -->
  80. <div class="modal fade" tabindex="-1" role="dialog" id="update_task_model">
  81. <div class="modal-dialog" role="document">
  82. <div class="modal-content">
  83. <div class="modal-header">
  84. <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
  85. aria-hidden="true">&times;</span></button>
  86. <h4 class="modal-title">Update Task</h4>
  87. </div>
  88. <div class="modal-body">
  89. <div class="alert alert-danger" v-if="errors.length > 0">
  90. <ul>
  91. <li v-for="error in errors">{{ error }}</li>
  92. </ul>
  93. </div>
  94. <div class="form-group">
  95. <label>Name:</label>
  96. <input type="text" placeholder="Task Name" class="form-control"
  97. v-model="update_task.name">
  98. </div>
  99. <div class="form-group">
  100. <label for="description">Description:</label>
  101. <textarea cols="30" rows="5" class="form-control"
  102. placeholder="Task Description" v-model="update_task.description"></textarea>
  103. </div>
  104. </div>
  105. <div class="modal-footer">
  106. <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
  107. <button type="button" @click="updateTask" class="btn btn-primary">Submit</button>
  108. </div>
  109. </div><!-- /.modal-content -->
  110. </div><!-- /.modal-dialog -->
  111. </div><!-- /.modal -->
  112. </div>
  113. </template>
  114. <script>
  115. export default {
  116. data(){
  117. return {
  118. task: {
  119. name: '',
  120. description: ''
  121. },
  122. errors: [],
  123. tasks: [],
  124. update_task: {}
  125. }
  126. },
  127. mounted()
  128. {
  129. this.readTasks();
  130. },
  131. methods: {
  132. deleteTask(index)
  133. {
  134. let conf = confirm("Do you ready want to delete this task?");
  135. if (conf === true) {
  136. axios.delete('/task/' + this.tasks[index].id)
  137. .then(response => {
  138. this.tasks.splice(index, 1);
  139. })
  140. .catch(error => {
  141. });
  142. }
  143. },
  144. initAddTask()
  145. {
  146. $("#add_task_model").modal("show");
  147. },
  148. createTask()
  149. {
  150. axios.post('/task', {
  151. name: this.task.name,
  152. description: this.task.description,
  153. })
  154. .then(response => {
  155. this.reset();
  156. this.tasks.push(response.data.task);
  157. $("#add_task_model").modal("hide");
  158. })
  159. .catch(error => {
  160. this.errors = [];
  161. if (error.response.data.errors && error.response.data.errors.name) {
  162. this.errors.push(error.response.data.errors.name[0]);
  163. }
  164. if (error.response.data.errors && error.response.data.errors.description)
  165. {
  166. this.errors.push(error.response.data.errors.description[0]);
  167. }
  168. });
  169. },
  170. reset()
  171. {
  172. this.task.name = '';
  173. this.task.description = '';
  174. },
  175. readTasks()
  176. {
  177. axios.get('http://127.0.0.1:8000/task')
  178. .then(response => {
  179. this.tasks = response.data.tasks;
  180. });
  181. },
  182. initUpdate(index)
  183. {
  184. this.errors = [];
  185. $("#update_task_model").modal("show");
  186. this.update_task = this.tasks[index];
  187. },
  188. updateTask()
  189. {
  190. axios.patch('/task/' + this.update_task.id, {
  191. name: this.update_task.name,
  192. description: this.update_task.description,
  193. })
  194. .then(response => {
  195. $("#update_task_model").modal("hide");
  196. })
  197. .catch(error => {
  198. this.errors = [];
  199. if (error.response.data.errors.name) {
  200. this.errors.push(error.response.data.errors.name[0]);
  201. }
  202. if (error.response.data.errors.description) {
  203. this.errors.push(error.response.data.errors.description[0]);
  204. }
  205. });
  206. }
  207. }
  208. }
  209. </script>

Now run the following command to compile the newly added code as a Vue.js component:

  1. npm run dev

 

Conclusion

This Laravel Vue single-page app is a simple demonstration of how to combine Laravel Vue JS into an effective frontend and backend. I am sure you could easily extend this idea into a powerful application that simplifies development. Do give this Vue JS and Laravel SPA tutorial a try and let me know how it went in the comments below.
Make sure to leave a comment if you need help in understanding the Laravel SPA code or the idea.

Comments