Ever since I have posted ExtJS 4 MVC CRUD tutorial, I got hundreds of request on writing the same example with PHP so I have decided to post a same article with Laravel. Those who are not familiar with Laravel should know that it’s a PHP MVC framework. Compare to Spring framework, I find very fast and easy to develop in Laravel because of Its controller, routes and Eloquent. So let’s start with Laravel first.
Download and install Laravel on your machine. I am using Laravel 4.2 version and installed it using composer.
First steps is to create a books table on DB. You can use Laravel migration or JefferyWay’s Generator class to generate table. If you are not familiar either of those then don’t worry, execute the following sql command will create a table on Database.
1
2
3
4
5
6
7
8
|
CREATE TABLE IF NOT EXISTS
tbl_books ( id int(10) NOT NULL AUTO_INCREMENT, title varchar(100) NOT NULL, author varchar(100) NOT NULL, price int(10) NOT NULL, quantity int(10) NOT NULL, PRIMARY KEY (
id))
|
Now create a Book Model which will look similar to below.
1
2
3
4
5
6
7
8
9
10
|
class Book extends Eloquent {
protected $table = ‘tbl_books’;
public $timestamps = false;
public $guarded = array();
protected $fillable = array(‘title’,
‘author’, ‘price’, ‘quantity’);
}
|
BookController used to perform CRUD operation on DB using Eloquent.
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
|
class BookController extends Controller {
public function load()
{
$books = Book::take(20)->orderBy(‘id’, ‘DESC’)->get();
return Response::jsend(‘success’, $books);
}
public function create()
{
$all = Input::all();
//if id = ”, create Book, else Update it.
if($all[‘id’] == ”)
{
Book::create($all);
return Response::jsend(‘success’,
array(‘msg’ => ‘New Book record successfully created.’)
);
}
else
{
$book = Book::where(‘id’, ‘=’, $all[‘id’]);
$book->update($all);
return Response::jsend(‘success’,
array(‘msg’ => ‘Book record successfully updated.’)
);
}
}
public function delete($bookId)
{
$book = Book::where(‘id’, ‘=’, $bookId);
$book->delete();
}
}
|
following controller entry in route.php file.
1
2
3
4
5
6
7
8
|
Route::get(‘books/load_books’, ‘BookController@load’);
Route::post(‘books/create’, ‘BookController@create’);
Route::get(‘books/delete/{bookId}’, ‘BookController@delete’);
Route::get(‘/’, function()
{
return View::make(‘index’);
});
|
Now ExtJS javascript code what use to create grid on client side and send data using ajax request.
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
|
Ext.onReady(function () {
Ext.define(‘TechZoo.model.Book’, {
extend: ‘Ext.data.Model’,
fields: [
{name: ‘id’, type: ‘int’},
{name: ‘title’, type: ‘string’},
{name: ‘author’, type: ‘string’},
{name: ‘price’, type: ‘int’},
{name: ‘quantity’, type: ‘int’}
]
});
Ext.define(‘TechZoo.store.Books’, {
extend : ‘Ext.data.Store’,
model : ‘TechZoo.model.Book’,
proxy : {
type : ‘ajax’,
url : ‘books/load_books’,
reader: {
type: ‘json’,
root: ‘data’
}
},
autoLoad: true
});
Ext.define(‘TechZoo.view.BooksList’, {
extend : ‘Ext.grid.Panel’,
alias : ‘widget.bookslist’,
title : ‘Books List – (ExtJS 4 Laravel CRUD example – @ Tousif Khan)’,
store : ‘Books’,
initComponent: function () {
this.tbar = [{
text : ‘Create New Book’,
action : ‘add’,
iconCls : ‘book-add’
}];
this.columns = [
{ header: ‘Title’, dataIndex: ‘title’, flex: 1 },
{ header: ‘Author’, dataIndex: ‘author’ },
{ header: ‘Price’, dataIndex: ‘price’ , width: 60 },
{ header: ‘Quantity’, dataIndex: ‘quantity’, width: 80 },
{ header: ‘Action’, width: 50, xtype:‘actioncolumn’,
items : [{
icon : ‘images/delete.png’,
tooltip : ‘Edit’,
handler : function(gView, rowIndex, colIndex) {
var grid = gView.up(‘grid’);
grid.deleteBook(grid, grid.getStore().getAt(rowIndex));
}
}]
}
];
this.callParent(arguments);
},//initComponent
deleteBook: function(grid, record) {
var data = record.getData();
if (grid) {
Ext.Msg.confirm(‘Remove Book’,
‘Are you sure you want to delete?’,
function (button) {
if (button == ‘yes’) {
//grid.store.remove(rowIndex);
Ext.Ajax.request({
url : ‘books/delete/’+data.id,
success : function(response) {
grid.getStore().load();
},
failure: function(response) {
Ext.Msg.alert(‘Failure’, ‘Failed to delete Book details.’);
}
});
}
});
}
}//deleteBook
});
Ext.define(‘TechZoo.view.BooksForm’, {
extend : ‘Ext.window.Window’,
alias : ‘widget.booksform’,
title : ‘Add Book’,
width : 350,
layout : ‘fit’,
resizable: false,
closeAction: ‘hide’,
modal : true,
config : {
recordIndex : 0,
action : ”
},
items : [{
xtype : ‘form’,
layout: ‘anchor’,
bodyStyle: {
background: ‘none’,
padding: ’10px’,
border: ‘0’
},
defaults: {
xtype : ‘textfield’,
anchor: ‘100%’
},
items : [{
name : ‘id’,
xtype : ‘hiddenfield’
},{
name : ‘title’,
fieldLabel: ‘Book Title’
},{
name : ‘author’,
fieldLabel: ‘Author Name’
},{
name : ‘price’,
fieldLabel: ‘Price’
},{
name : ‘quantity’,
fieldLabel: ‘Quantity’
}]
}],
buttons: [{
text: ‘OK’,
action: ‘add’
},{
text : ‘Reset’,
handler : function () {
this.up(‘window’).down(‘form’).getForm().reset();
}
},{
text : ‘Cancel’,
handler: function () {
this.up(‘window’).close();
}
}]
});
Ext.define(‘TechZoo.controller.Books’, {
extend : ‘Ext.app.Controller’,
stores : [‘Books’],
views : [‘BooksList’, ‘BooksForm’],
refs : [{
ref : ‘formWindow’,
xtype : ‘booksform’,
selector : ‘booksform’,
autoCreate: true
}],
init: function () {
this.control({
‘bookslist > toolbar > button[action=add]’: {
click: this.showAddForm
},
‘bookslist’: {
itemdblclick: this.onRowdblclick
},
‘booksform button[action=add]’: {
click: this.doAddBook
}
});
},
onRowdblclick: function(me, record, item, index) {
var win = this.getFormWindow();
win.setTitle(‘Edit Book’);
win.setAction(‘edit’);
win.setRecordIndex(index);
win.down(‘form’).getForm().setValues(record.getData());
win.show();
},
showAddForm: function () {
var win = this.getFormWindow();
win.setTitle(‘Add Book’);
win.setAction(‘add’);
win.down(‘form’).getForm().reset();
win.show();
},
doAddBook: function () {
var win = this.getFormWindow();
var store = this.getBooksStore();
var values = win.down(‘form’).getValues();
var action = win.getAction();
var book = Ext.create(‘TechZoo.model.Book’, values);
//call Ajax request to create/update book record.
Ext.Ajax.request({
url : ‘books/create’,
method : ‘POST’,
jsonData : values,
success : function(response) {
var resp = Ext.JSON.decode(response.responseText);
Ext.Msg.show({
title : ‘Confirmation’,
msg : resp.data.msg,
width : 400,
buttons: Ext.Msg.OK,
fn : function(btn) {
if(btn == ‘ok’) {
store.load();
win.close();
}
},
icon : Ext.MessageBox.INFO
});
},
failure: function(response) {
Ext.Msg.alert(‘Failure’, ‘Failed to create/update Book details.’);
win.close();
}
});
}
});
Ext.application({
name : ‘TechZoo’,
controllers: [‘Books’],
launch: function () {
Ext.widget(‘bookslist’, {
width : 500,
height: 300,
renderTo: ‘output’
});
}
}
);
});
|
Output will look similar to screenshot below.
Source techzoo.org