Laravel has become the most popular choice for developing PHP projects. One important reason for this popularity is the built in support for Vue.js, a very fast growing JavaScript library for developing impressive front-ends.
This combination results is fast, secure and very 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.
Prerequisites
For the purpose of this tutorial, I assume that you have a Laravel application installed on a web server. My setup is:
- WAMP/XAMPP environment
- Laravel 5.5
- PHP 7.1
- MySQL
- Node.js with NPM
To make sure that that I don’t get distracted by server level issues, I decided to host my Laravel on Cloudways managed servers because it takes care of server level issues and has a great devstack right out of the box. You can try out Cloudways for free by signing for an account and then following this simple GIF for setting up the server and the Laravel application.
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
2
|
npm init
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
2
3
|
cd /path–to–project/project–name
php artisan make:migration create_tasks_table —create=tasks
|
Next , open the migration file located in the database/migration folder and replace the up() function with the following code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
public function up()
{
Schema::create(‘tasks’, function (Blueprint $table) {
$table->increments(‘id’);
$table->string(‘name’);
$table->unsignedInteger(‘user_id’);
$table->text(‘description’);
$table->timestamps();
});
}
|
Next , In the app/Providers/AppServiceProvider.php file, the boot method sets a default string length:
1
2
3
4
5
6
7
8
9
10
11
|
use Illuminate\Support\Facades\Schema;
public function boot()
{
Schema::defaultStringLength(191);
}
|
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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
|
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Contracts\Validation\Validator;
class Task extends Model
{
protected $fillable = [
‘name’,
‘user_id’,
‘description’,
];
}
|
The Code for Controller
Next, update the controller file with the following code.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
|
<?php
namespace App\Http\Controllers;
use App\Task;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class TaskController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$tasks = Task::where([‘user_id’ => Auth::user()->id])->get();
return response()->json([
‘tasks’ => $tasks,
], 200);
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
//
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
}
/**
* Display the specified resource.
*
* @param \App\Task $task
* @return \Illuminate\Http\Response
*/
public function show(Task $task)
{
//
}
/**
* Show the form for editing the specified resource.
*
* @param \App\Task $task
* @return \Illuminate\Http\Response
*/
public function edit(Task $task)
{
//
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param \App\Task $task
* @return \Illuminate\Http\Response
*/
public function update(Request $request, Task $task)
{
}
/**
* Remove the specified resource from storage.
*
* @param \App\Task $task
* @return \Illuminate\Http\Response
*/
public function destroy(Task $task)
{
}
}
|
Middleware
To setup middleware, add the following code to the Task Controller.
1
2
3
4
5
6
7
|
public function __construct()
{
$this->middleware(‘auth’);
}
|
Create the Method
In the store() method of Task Controller, update the following code to add data into database.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
|
$this->validate($request, [
‘name’ => ‘required’,
‘description’ => ‘required’,
]);
$task = Task::create([
‘name’ => request(‘name’),
‘description’ => request(‘description’),
‘user_id’ => Auth::user()->id
]);
return response()->json([
‘task’ => $task,
‘message’ => ‘Success’
], 200);
|
Update Method
In Update() method of Task Controller, update the following code to edit database data. database.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
$this->validate($request, [
‘name’ => ‘required|max:255’,
‘description’ => ‘required’,
]);
$task->name = request(‘name’);
$task->description = request(‘description’);
$task->save();
return response()->json([
‘message’ => ‘Task updated successfully!’
], 200);
|
Delete Method
In the Destroy() method of Task Controller, the following code will delete data from the database.
1
2
3
4
5
6
7
|
$task->delete();
return response()->json([
‘message’ => ‘Task deleted successfully!’
], 200);
|
Route Set up in Laravel SPA
Routes are located in route/web.php and contains the following code:
1
2
3
|
Route::get(‘/home’, ‘HomeController@index’)->name(‘home’);
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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
|
Task.vue:
<template>
<div class=“container”>
<div class=“row”>
<div class=“col-md-12”>
<div class=“panel panel-default”>
<div class=“panel-heading”>My Assigments</div>
<div class=“panel-body”>
</div>
</div>
</div>
</div>
</div>
</template>
<script>
export default {
mounted() {
}
}
</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
2
3
|
app.js:
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
2
3
4
5
6
7
|
@extends(‘layouts.app’)
@section(‘content’)
<task></task>
@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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
|
<template>
<div class=“container”>
<div class=“row”>
<div class=“col-md-12”>
<div class=“panel panel-default”>
<div class=“panel-heading”>
<h3><span class=“glyphicon glyphicon-dashboard”></span> Assignment Dashboard </h3> <br>
<button @click=“initAddTask()” class=“btn btn-success “ style=“padding:5px”>
Add New Assignment
</button>
</div>
<div class=“panel-body”>
<table class=“table table-bordered table-striped table-responsive” v–if=“tasks.length > 0”>
<tbody>
<tr>
<th>
No.
</th>
<th>
Name
</th>
<th>
Description
</th>
<th>
Action
</th>
</tr>
<tr v–for=“(task, index) in tasks”>
<td>{{ index + 1 }}</td>
<td>
{{ task.name }}
</td>
<td>
{{ task.description }}
</td>
<td>
<button @click=“initUpdate(index)” class=“btn btn-success btn-xs” style=“padding:8px”><span class=“glyphicon glyphicon-edit”></span></button>
<button @click=“deleteTask(index)” class=“btn btn-danger btn-xs” style=“padding:8px”><span class=“glyphicon glyphicon-trash”></span></button>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
<div class=“modal fade” tabindex=“-1” role=“dialog” id=“add_task_model”>
<div class=“modal-dialog” role=“document”>
<div class=“modal-content”>
<div class=“modal-header”>
<button type=“button” class=“close” data–dismiss=“modal” aria–label=“Close”><span
aria–hidden=“true”>×</span></button>
<h4 class=“modal-title”>Add New Task</h4>
</div>
<div class=“modal-body”>
<div class=“alert alert-danger” v–if=“errors.length > 0”>
<ul>
<li v–for=“error in errors”>{{ error }}</li>
</ul>
</div>
<div class=“form-group”>
<label for=“names”>Name:</label>
<input type=“text” name=“name” id=“name” placeholder=“Task Name” class=“form-control”
v–model=“task.name”>
</div>
<div class=“form-group”>
<label for=“description”>Description:</label>
<textarea name=“description” id=“description” cols=“30” rows=“5” class=“form-control”
placeholder=“Task Description” v–model=“task.description”></textarea>
</div>
</div>
<div class=“modal-footer”>
<button type=“button” class=“btn btn-default” data–dismiss=“modal”>Close</button>
<button type=“button” @click=“createTask” class=“btn btn-primary”>Submit</button>
</div>
</div><!— /.modal–content —>
</div><!— /.modal–dialog —>
</div><!— /.modal —>
<div class=“modal fade” tabindex=“-1” role=“dialog” id=“update_task_model”>
<div class=“modal-dialog” role=“document”>
<div class=“modal-content”>
<div class=“modal-header”>
<button type=“button” class=“close” data–dismiss=“modal” aria–label=“Close”><span
aria–hidden=“true”>×</span></button>
<h4 class=“modal-title”>Update Task</h4>
</div>
<div class=“modal-body”>
<div class=“alert alert-danger” v–if=“errors.length > 0”>
<ul>
<li v–for=“error in errors”>{{ error }}</li>
</ul>
</div>
<div class=“form-group”>
<label>Name:</label>
<input type=“text” placeholder=“Task Name” class=“form-control”
v–model=“update_task.name”>
</div>
<div class=“form-group”>
<label for=“description”>Description:</label>
<textarea cols=“30” rows=“5” class=“form-control”
placeholder=“Task Description” v–model=“update_task.description”></textarea>
</div>
</div>
<div class=“modal-footer”>
<button type=“button” class=“btn btn-default” data–dismiss=“modal”>Close</button>
<button type=“button” @click=“updateTask” class=“btn btn-primary”>Submit</button>
</div>
</div><!— /.modal–content —>
</div><!— /.modal–dialog —>
</div><!— /.modal —>
</div>
</template>
<script>
export default {
data(){
return {
task: {
name: ”,
description: ”
},
errors: [],
tasks: [],
update_task: {}
}
},
mounted()
{
this.readTasks();
},
methods: {
deleteTask(index)
{
let conf = confirm(“Do you ready want to delete this task?”);
if (conf === true) {
axios.delete(‘/task/’ + this.tasks[index].id)
.then(response => {
this.tasks.splice(index, 1);
})
.catch(error => {
});
}
},
initAddTask()
{
$(“#add_task_model”).modal(“show”);
},
createTask()
{
axios.post(‘/task’, {
name: this.task.name,
description: this.task.description,
})
.then(response => {
this.reset();
this.tasks.push(response.data.task);
$(“#add_task_model”).modal(“hide”);
})
.catch(error => {
this.errors = [];
if (error.response.data.errors && error.response.data.errors.name) {
this.errors.push(error.response.data.errors.name[0]);
}
if (error.response.data.errors && error.response.data.errors.description)
{
this.errors.push(error.response.data.errors.description[0]);
}
});
},
reset()
{
this.task.name = ”;
this.task.description = ”;
},
readTasks()
{
axios.get(‘http://127.0.0.1:8000/task’)
.then(response => {
this.tasks = response.data.tasks;
});
},
initUpdate(index)
{
this.errors = [];
$(“#update_task_model”).modal(“show”);
this.update_task = this.tasks[index];
},
updateTask()
{
axios.patch(‘/task/’ + this.update_task.id, {
name: this.update_task.name,
description: this.update_task.description,
})
.then(response => {
$(“#update_task_model”).modal(“hide”);
})
.catch(error => {
this.errors = [];
if (error.response.data.errors.name) {
this.errors.push(error.response.data.errors.name[0]);
}
if (error.response.data.errors.description) {
this.errors.push(error.response.data.errors.description[0]);
}
});
}
}
}
</script>
|
Now run the following command to compile the newly added code as a Vue.js component:
1
|
npm run dev
|