Anda di halaman 1dari 57

9/20/2015

CreateaLaravelandAngularSinglePageCommentApplication|Scotch

(/)

Create a Laravel and


Angular Single Page
Comment Application
Chris Sevilleja ( (https://scotch.io/author/chris)@sevilayha (https://twitter.com/sevilayha))
February 4, 2014

158

Tutorials (https://scotch.io/category/tutorials)

laravel

(https://scotch.io/tag/laravel), SPA (https://scotch.io/tag/spa)

FAVORIT

WPFPACTION=ADD&

61
shares
30

31

https://scotch.io/tutorials/createalaravelandangularsinglepagecommentapplication

1/57

9/20/2015

CreateaLaravelandAngularSinglePageCommentApplication|Scotch

VIEW CODE

(HTTPS://GITHUB.COM/SCOTCHIO/LARAVEL-ANGULARCOMMENT-APP)

30

31

AD

AngularJSexperts

UKbasedAngularJSdevelopersCallusforafreeconsultation
VIEW CODE

(HTTPS://GITHUB.COM/SCOTCH-

AdvertiseHere(http://buysellads.com/buy/detail/219041/zone/1300582?
IO/LARAVEL-ANGULARutm_source=site_219041&utm_medium=website&utm_campaign=imagetext&utm_content=zone_1300582)

COMMENT-APP)

OUTLINE

and
What WellLaravel
Be Building

Angular have

both become very well


renowned tools in the web

(//srv.buysellads.com/a

development world lately.


Laravel for the great things
it brings to the PHP
community and Angular for

(//srv.buysellads.com/ads/click/x/G
(//srv.buy

the amazing frontend tools


and its simplicity. Combining
these two great frameworks
only seems like the logical
next step.

https://scotch.io/tutorials/createalaravelandangularsinglepagecommentapplication

(//srv.buysellads.com/ads/click/x/G
(//srv.buy

2/57

9/20/2015

CreateaLaravelandAngularSinglePageCommentApplication|Scotch

For our use cases, we will be


Scroll to Top

using Laravel as the


RESTful API backend and

(https://www.fa
(https://tw
(http

Angular as the frontend to


create a very simple single
page comment application.
This will be a simple
example to show off how to
get started using these two
technologies so dont hope
for any extra database stuff
on how to handle subcomments or anything like
that.

What Well Be
Building

(https://scotch.io/boo

your-first-node-js-

Subscribe and get our FRE

Build Your First Node.j

(https://scotch.io/books

your-first-node-js-ap
Email Address
Subscribe

This will be a simple single


page comment application:
RESTful Laravel API to
handle getting, creating,
and deleting comments
Angular frontend to
https://scotch.io/tutorials/createalaravelandangularsinglepagecommentapplication

POPULAR ON SCOT

Whats New in B
3/57

9/20/2015

CreateaLaravelandAngularSinglePageCommentApplication|Scotch

handle showing our

(https://scotch.io

creation form and the

talk/whats-new-

comments
Ability to create a
comment and see it

bootstrap-4)
Getting Started

An Interactive G

added to our list w/o

(https://scotch.io/tutorials/get

page refresh

started-with-vim-an-interactiv

Ability to delete a
comment and see it
removed from our list
w/o page refresh

Announcing Sco

2.0 Our Dead-

Vagrant LAMP S
Improved

(https://scotch.io/bar-talk/ann

scotch-box-2-0-our-dead-simp

Overall, these are very


simple concepts. Our focus

vagrant-lamp-stack-improved

How to Build a W
Plugin (part 1)

will be to see the


intricacies of how Laravel

(https://scotch.io/tutorials/ho

and Angular can work

build-a-wordpress-plugin-par

together.

Build an App wit

A Lightweight Al
to AngularJS

(https://scotch.io/tutorials/bu

app-with-vue-js-a-lightweightalternative-to-angularjs)
Building a Slack

Node.js and Chu


Super Powers

(https://scotch.io/tutorials/bu

slack-bot-with-node-js-and-ch
norris-super-powers)
https://scotch.io/tutorials/createalaravelandangularsinglepagecommentapplication

4/57

9/20/2015

CreateaLaravelandAngularSinglePageCommentApplication|Scotch

(https://cask.scotch.io/2014/

Build an Etsy Clo

02/laravel-angular-single-

(Part 1)

page-application1.jpg)

Angular and Sta

(https://scotch.io/tutorials/bu

etsy-clone-with-angular-and-s

The Laravel
Backend

part-1)

Setting Up Laravel
Go ahead and get your
Laravel setup ready. Well be
doing some basic things to
get our backend to do CRUD
on comments:
Create a database
migration
Seed our database with
sample comments
Create our routes for
our API
Creating a catch-all
route to let Angular
handle routing
Creating a resource
controller for comments

Getting our Database

https://scotch.io/tutorials/createalaravelandangularsinglepagecommentapplication

(//srv.buysellads.com/ads/click/x/GT
AdvertiseHere

(http://buysellads.com/buy/detail/21904

5/57

9/20/2015

CreateaLaravelandAngularSinglePageCommentApplication|Scotch

Getting our Database


Ready Migrations

LEARN NODE AND ANG


WITH OUR EBOO

We will need a simple


structure for our comments.
We just need text and
author. Lets create our
Laravel migration to create
our comments.
Lets run the artisan
command that will create
our comments migration so
that we can create the table
in our database:

(http://bit.ly/1FxJ

phpartisanmigrate:make

A VAGRANT LAMP ST
THAT JUST WORK

create_comments_table
create=comments

Well use the Laravel


Schema Builder
(http://laravel.com/docs/sch
ema) to create the text and
author fields that we need.
Laravel will also create the
id column and the
https://scotch.io/tutorials/createalaravelandangularsinglepagecommentapplication

6/57

9/20/2015

CreateaLaravelandAngularSinglePageCommentApplication|Scotch

timestamps so that we
know how long ago the
comment was made. Here is
the code for the comments
table:

//app/database/migrations/####_##_##_######_create_comments_table.php
...
/**
*Runthemigrations.
*
*@returnvoid
*/

15
16

publicfunctionup()
{
Schema::create('comments',function
{
$table>increments('id');

(http://bit.ly/1PY0

DEAD SIMPLE
OFF-CANVAS PANE

$table>string('text');
$table>string('author');

$table>timestamps();
});
}

...

https://scotch.io/tutorials/createalaravelandangularsinglepagecommentapplication

7/57

9/20/2015

CreateaLaravelandAngularSinglePageCommentApplication|Scotch

Make sure you go adjust


your database settings in
app/config/database.php

(http://bit.ly/1QJLL

SCOTCH.IO STICKER

with the right credentials.


Now we will run the
migration so that we create
this table with the columns
that we need:
phpartisanmigrate

(https://cask.scotch.io/2014/

(http://shop.scotc

02/laravel-angularmigrate.jpg)
With our table made, lets
create an Eloquent model so
that we can interact with it.

Comment Model

AngularJS exper

UK based AngularJS developers


Call us for a free consultation
www.byng.co

https://scotch.io/tutorials/createalaravelandangularsinglepagecommentapplication

8/57 IN
AUTOMATED ONLINE

9/20/2015

CreateaLaravelandAngularSinglePageCommentApplication|Scotch

We will be using Laravel

AUTOMATED ONLINE IN

Eloquent
(http://laravel.com/docs/elo
quent) models to interact
with our database. This will
be very easy to do. Lets
create a model:
app/models/Comment.php .

(https://invoicebus.com
aff=8hlimbxx)

<?php
//app/models/Comment.php

(https://www.facebook
(https://twitter.co
(https://feed

classCommentextendsEloquent{//leteloquentknowthattheseattribu

We now have our new table


and model. Lets fill it with
some sample data using
Laravel Seeding
(http://laravel.com/docs/mig
rations#database-seeding).

Seeding Our Database

https://scotch.io/tutorials/createalaravelandangularsinglepagecommentapplication

9/57

9/20/2015

CreateaLaravelandAngularSinglePageCommentApplication|Scotch

We will need a few


comments so that we can
test a few things. Lets create
a seed file and fill our
database with 3 sample
comments.
Create a file:
app/database/seeds/Comment
TableSeeder.php and fill it

with this code.

https://scotch.io/tutorials/createalaravelandangularsinglepagecommentapplication

10/57

9/20/2015

CreateaLaravelandAngularSinglePageCommentApplication|Scotch

<?php//app/database/seeds/CommentTableSeeder.php
classCommentTableSeederextendsSeeder{
publicfunctionrun()
{
DB::table('comments')>delete();

Comment::create(array(
'author'=>'ChrisSevilleja',
'text'=>'LookIamatestcomment.'
));

Comment::create(array(
'author'=>'NickCerminara',
'text'=>'Thisisgoingtobesupercrazy.'
));

Comment::create(array(
'author'=>'HollyLloyd',
'text'=>'IamamasterofLaravelandAngular.'
));
}
}

To call this Seeder file, lets


open
app/database/seeds/Databas
eSeeder.php and add the

following:
https://scotch.io/tutorials/createalaravelandangularsinglepagecommentapplication

11/57

9/20/2015

CreateaLaravelandAngularSinglePageCommentApplication|Scotch

//app/database/seeds/DatabaseSeeder.php

...
/**
*Runthedatabaseseeds.
*
*@returnvoid
*/
publicfunctionrun()
13

{
Eloquent::unguard();

$this>call('CommentTableSeeder');
$this>command>info('Commenttableseeded.'
}

...

Now lets run our seeders


using artisan.
phpartisandb:seed

https://scotch.io/tutorials/createalaravelandangularsinglepagecommentapplication

12/57

9/20/2015

CreateaLaravelandAngularSinglePageCommentApplication|Scotch

(https://cask.scotch.io/2014/
02/laravel-angular-databaseseed.jpg)
Now we have a database
with a comment table, an
Eloquent model, and
samples in our database.
Not bad for a days work
but were not even close to
done yet.

Comment Resource
Controller
app/controllers/CommentController.php

We will use Laravels


resource controllers
(http://laravel.com/docs/con
trollers) to handle our API
functions for comments.
Since well be using Angular
to display a resource and
show create and update
forms, well create a

https://scotch.io/tutorials/createalaravelandangularsinglepagecommentapplication

13/57

9/20/2015

CreateaLaravelandAngularSinglePageCommentApplication|Scotch

resource controller with


artisan without the create
or edit functions.
Lets create our controller
using artisan.
phpartisan
controller:make
CommentController
only=index,store,destroy

For our demo app, well only


be using these three
functions in our resource
controller. To expand on this
youd want to include all the
functions like update, show,

update for a more fully


fledged app.

https://scotch.io/tutorials/createalaravelandangularsinglepagecommentapplication

14/57

9/20/2015

CreateaLaravelandAngularSinglePageCommentApplication|Scotch

(https://cask.scotch.io/2014/
02/laravel-angular-createcontroller.jpg)
Now weve created our
controller. We dont need
the create and edit
functions because Angular
will be handling showing
those forms, not Laravel.
Laravel is just responsible
for sending data back to our
frontend. We also took out
the update function for this
demo just because we want
to keep things simple. Well
handle creating, showing,
and deleting comments.
To send data back, we will
want to send all our data
back as JSON. Lets go
through our newly created
controller and fill out our
functions accordingly.

https://scotch.io/tutorials/createalaravelandangularsinglepagecommentapplication

15/57

9/20/2015

CreateaLaravelandAngularSinglePageCommentApplication|Scotch

<?php//app/controllers/CommentController.php
classCommentControllerextends\BaseController
/**
*SendbackallcommentsasJSON
*
*@returnResponse
*/
publicfunctionindex()
{
returnResponse::json(Comment::get(
}

/**
*Storeanewlycreatedresourceinstorage.
*
*@returnResponse
*/
publicfunctionstore()
{
Comment::create(array(
'author'=>Input::get('author'
'text'=>Input::get('text')
));

returnResponse::json(array('success'
}

/**
*Removethespecifiedresourcefromstorage.
*
*@paramint$id
*@returnResponse
*/
publicfunctiondestroy($id)
https://scotch.io/tutorials/createalaravelandangularsinglepagecommentapplication

16/57

9/20/2015

CreateaLaravelandAngularSinglePageCommentApplication|Scotch

publicfunctiondestroy($id)
{
Comment::destroy($id);

returnResponse::json(array('success'
}

You can see how easy it is to


handle CRUD with Laravel
and Eloquent. Its incredibly
simple to handle all the
functions that we need.
With our controller ready to
go, the last thing we need to
do for our backend is
routing.
Extra Reading: Simple
Laravel CRUD with Resource
Controllers
(https://scotch.io/tutorials/si
mple-laravel-crud-withresource-controllers)

Our Routes app/routes.php


https://scotch.io/tutorials/createalaravelandangularsinglepagecommentapplication

17/57

9/20/2015

CreateaLaravelandAngularSinglePageCommentApplication|Scotch

With our database ready to


rock and roll, lets handle
the routes of our Laravel
application. We will need
routes to send users to the
Angular frontend since that
will have its own routing. We
will also need routes for our
backend API so people can
access our comment data.
Lets create the Angular
pointing routes. We will
need one for the home
page and a catch-all route
to send users to Angular.
This ensures that any way a
user accesses our site, they
will be routed to the Angular
frontend.
Well be prefixing our API
routes with (drumroll
please) api . This way, if
somebody wants to get all
comments, they will use the
https://scotch.io/tutorials/createalaravelandangularsinglepagecommentapplication

18/57

9/20/2015

CreateaLaravelandAngularSinglePageCommentApplication|Scotch

URL:
http://example.com/api/com
ments . This just makes sense

moving forward and is some


basic API creation good
tactics.

https://scotch.io/tutorials/createalaravelandangularsinglepagecommentapplication

19/57

9/20/2015

CreateaLaravelandAngularSinglePageCommentApplication|Scotch

<?php//app/routes.php
//HOMEPAGE===================================
//wedontneedtouseLaravelBlade
//wewillreturnaPHPfilethatwillholdallofourAngularcontent

//seethe"WheretoPlaceAngularFiles"belowtoseeideasonhowtos
Route::get('/',function(){
View::make('index');//willreturnapp/views/index.php
});

//APIROUTES==================================
Route::group(array('prefix'=>'api'),function

//sincewewillbeusingthisjustforCRUD,wewon'tneedcreatea
//Angularwillhandlebothofthoseforms

//thisensuresthatausercan'taccessapi/createorapi/editwhen
Route::resource('comments','CommentController'
array('only'=>array('index','store'

});
//CATCHALLROUTE=============================

//allroutesthatarenothomeorapiwillberedirectedtothefronten
//thisallowsangulartoroutethem
App::missing(function($exception){
returnView::make('index');
});

We now have our routes to


handle the 3 main things
our Laravel backend needs
to do.

https://scotch.io/tutorials/createalaravelandangularsinglepagecommentapplication

20/57

9/20/2015

CreateaLaravelandAngularSinglePageCommentApplication|Scotch

Handling Catch-All
Routes: In Laravel, you
can do this a few ways.
Usually it isnt ideal to do
the above code and have
a catch-all for your entire
application. The
alternative is that you
can use Laravel
Controller Missing
Methods
(http://laravel.com/docs/controllers#handlingmissing-methods) to
catch routes.
Testing All Our Routes
Lets make sure we have all
the routes we need. Well
use artisan and see all our
routes:
phpartisanroutes

This command will let us see


our routes and sort of a topdown view of our
application.
https://scotch.io/tutorials/createalaravelandangularsinglepagecommentapplication

21/57

9/20/2015

CreateaLaravelandAngularSinglePageCommentApplication|Scotch

(https://cask.scotch.io/2014/
02/laravel-angular-artisanroutes.jpg)
We can see the HTTP verb
and the route used to get all
comments, get a single
comment, create a
comment, and destroy a
comment. On top of those
API routes, we can also see
how a user get routed to our
Angular application by the
home page route.

Backend Done
Finally! Our Laravel API
backend is done. We have
done so much and yet,
theres still so much to do.
We have set up our
database and seeded it,
https://scotch.io/tutorials/createalaravelandangularsinglepagecommentapplication

22/57

9/20/2015

CreateaLaravelandAngularSinglePageCommentApplication|Scotch

created our models and


controllers, and created
our routes. Lets move onto
the frontend Angular work.

Where to Place
Angular Files
Ive seen this question asked
a lot. Where exactly should I
be putting Angular files and
how does Laravel and
Angular work together. We
did an article on getting
Laravel Blade and Angular to
work together
(https://scotch.io/bartalk/quick-tip-using-laravelblade-with-angularjs). This
article works under the
assumption that we arent
even going to use Blade.
To let Angular handle the
frontend, we will need
Laravel to pass our user to
https://scotch.io/tutorials/createalaravelandangularsinglepagecommentapplication

23/57

9/20/2015

CreateaLaravelandAngularSinglePageCommentApplication|Scotch

our index.php file. We can


place this in a few different
places. By default, when you
use:

//app/routes.php

Route::get('/',function(){
returnView::make('index');
});

This will return


app/views/index.php .

Laravel will by default look


in the app/views folder.
Some people may want to
keep Angular files
completely separate from
Laravel files. They will want
their entire application to be
housed inside of the public
folder. To do this is simple:
just change the default View

https://scotch.io/tutorials/createalaravelandangularsinglepagecommentapplication

24/57

9/20/2015

CreateaLaravelandAngularSinglePageCommentApplication|Scotch

location to the public folder.


This can be done in the
app/config/view.php file.

//app/config/view.php
...
//makelaravellookinpublic/viewsforviewfiles
'paths'=>array(__DIR__.'/../../public/views'

...

Now return
View::make('index') will

look for
public/views/index.php . It

is all preference on how


youd like to structure your
app. Some people see it as a
benefit to have the entire
Angular application in the
public folder so that it is
easier to handle routing and
if it is needed in the future,

https://scotch.io/tutorials/createalaravelandangularsinglepagecommentapplication

25/57

9/20/2015

CreateaLaravelandAngularSinglePageCommentApplication|Scotch

to completely separate the


backend RESTful API and the
Angular frontend.
For Angular routing, then
your partial files will be
placed in the public folder,
but thats out of the scope of
this article. For more
information on that kind of
single page Angular routing,
check out Single Page
Angular Application Routing
(https://scotch.io/tutorials/ja
vascript/single-page-appswith-angularjs-routing-andtemplating).
Lets assume we left
everything default and our
main view file is in our
app/views folder and move

forward.

Routing with Laravel


and Angular There are a
https://scotch.io/tutorials/createalaravelandangularsinglepagecommentapplication

26/57

9/20/2015

CreateaLaravelandAngularSinglePageCommentApplication|Scotch

lot of questions about


having routing with
Laravel and Angular and
if they conflict. Laravel
will handle the main
routing for your
application. Angular
routing will only happen
when Laravel routes our
user to the main Angular
route ( index.php ) in this
case. This is why we use
a Laravel catch-all route.
Laravel will handle the
API routes and anything
it doesnt know how to
route will be sent to
Angular. You can then
set up all the routing for
your Angular application
to handle showing
different views.

The Angular
Frontend

Getting Our

https://scotch.io/tutorials/createalaravelandangularsinglepagecommentapplication

27/57

9/20/2015

CreateaLaravelandAngularSinglePageCommentApplication|Scotch

Getting Our
Application Ready
Everything for our Angular
application will be handled
in the public folder. This
lets us keep a good
separation of the backend in
the app folder.
Lets look at the application
structure we will have in our
public folder. Weve

created our Angular


application to be modular
since that is best practices.
Now our separated parts of
our application will be easy
to test and work with.

https://scotch.io/tutorials/createalaravelandangularsinglepagecommentapplication

28/57

9/20/2015

CreateaLaravelandAngularSinglePageCommentApplication|Scotch

public/
js/
controllers///wherewewillputourangularcontrollers
mainCtrl.js
services///angularservices
commentService.js
app.js

Angular Service
public/js/services/commentService.js

Our Angular service is going


to be the primary place
where we will have our HTTP
calls to the Laravel API. It is
pretty straightforward and
we use the Angular $http
(http://docs.angularjs.org/ap
i/ng.$http) service.

https://scotch.io/tutorials/createalaravelandangularsinglepagecommentapplication

29/57

9/20/2015

CreateaLaravelandAngularSinglePageCommentApplication|Scotch

//public/js/services/commentService.js
angular.module('commentService',[])
.factory('Comment',function($http){
return{
//getallthecomments
get:function(){
return$http.get('/api/comments'
},
//saveacomment(passincommentdata)
save:function(commentData){
return$http({
method:'POST',
url:'/api/comments',
headers:{'ContentType':
data:$.param(commentData)
});
},
//destroyacomment
destroy:function(id){
return$http.delete('/api/comments/'
}
}
});

This is our Angular service


with 3 different functions.
These are the only functions
https://scotch.io/tutorials/createalaravelandangularsinglepagecommentapplication

30/57

9/20/2015

CreateaLaravelandAngularSinglePageCommentApplication|Scotch

we need since they will


correspond to the api routes
we made in our Laravel
routes.
We will be returning the
promise object from our
service. These will be dealt
with in our controllers. The
naming convention here
also stays the same as the
Laravel controller that we
have.
With our Angular Service
done, lets go into our
controller and use it.

Angular Controller
public/js/controllers/mainCtrl.js

The controller is where we


will have most of the
functionality for our
application. This is where we

https://scotch.io/tutorials/createalaravelandangularsinglepagecommentapplication

31/57

9/20/2015

CreateaLaravelandAngularSinglePageCommentApplication|Scotch

will create functions to


handle the submit forms
and deleting on our view.

https://scotch.io/tutorials/createalaravelandangularsinglepagecommentapplication

32/57

9/20/2015

CreateaLaravelandAngularSinglePageCommentApplication|Scotch

//public/js/controllers/mainCtrl.js
angular.module('mainCtrl',[])
//injecttheCommentserviceintoourcontroller
.controller('mainController',function($scope
//objecttoholdallthedataforthenewcommentform
$scope.commentData={};

//loadingvariabletoshowthespinningloadingicon
$scope.loading=true;

//getallthecommentsfirstandbindittothe$scope.commentsobj
//usethefunctionwecreatedinourservice
//GETALLCOMMENTS==============
Comment.get()
.success(function(data){
$scope.comments=data;
$scope.loading=false;
});
//functiontohandlesubmittingtheform
//SAVEACOMMENT================
$scope.submitComment=function(){
$scope.loading=true;
//savethecomment.passincommentdatafromtheform
//usethefunctionwecreatedinourservice
Comment.save($scope.commentData)
.success(function(data){

//ifsuccessful,we'llneedtorefreshthecommentlist
Comment.get()
.success(function(getData
$scope.comments=getData
$scope.loading=false
https://scotch.io/tutorials/createalaravelandangularsinglepagecommentapplication

33/57

9/20/2015

CreateaLaravelandAngularSinglePageCommentApplication|Scotch

$scope.loading=false
});
})
.error(function(data){
console.log(data);
});
};
//functiontohandledeletingacomment

//DELETEACOMMENT================================================
$scope.deleteComment=function(id){
$scope.loading=true;
//usethefunctionwecreatedinourservice
Comment.destroy(id)
.success(function(data){

//ifsuccessful,we'llneedtorefreshthecommentlist
Comment.get()
.success(function(getData
$scope.comments=getData
$scope.loading=false
});
});
};
});

As you can see in our


controller, we have injected
our Comment service and use
it for the main functions:
get , save , and delete .
https://scotch.io/tutorials/createalaravelandangularsinglepagecommentapplication

34/57

9/20/2015

CreateaLaravelandAngularSinglePageCommentApplication|Scotch

Using a service like this


helps to not pollute our
controller with $http gets
and puts.

Connecting Our
Application public/js/app.js
On the Angular side of
things, we have created our
service and our controller.
Now lets link everything
together so that we can
apply it to our application
using ngapp and ng
controller .

This will be the code to


create our Angular
application. We will inject
the service and controller
into. This is best practices
since it keeps our
application modular and
each different part can be
testable and extendable.
https://scotch.io/tutorials/createalaravelandangularsinglepagecommentapplication

35/57

9/20/2015

CreateaLaravelandAngularSinglePageCommentApplication|Scotch

//public/js/app.js

varcommentApp=angular.module('commentApp'

Thats it! Not much to it.


Now well actually get to our
view where we can see how
all these Angular parts work
together.

Our Main View


app/views/index.php

So far, after everything


weve done up to this point,
we still wont be able to see
anything in our browser. We
will need to define our view
file since Laravel in our
home route and our catchall route returns return
View::make('index'); .

https://scotch.io/tutorials/createalaravelandangularsinglepagecommentapplication

36/57

9/20/2015

CreateaLaravelandAngularSinglePageCommentApplication|Scotch

Lets go ahead and create


that view now. We will be
using all the Angular parts
that weve created. The main
parts that weve created
from Angular that well use
in index.php are:
ng-app and ngcontroller: Well apply
these to our application
by attaching them to
our body tag
ng-repeat: Well loop
over the comments and
display them in our
template
submitComment():
Well attach this
function to our form
using ngsubmit
Loading Icons: Well
create a variable called
loading . If it is set to

true, well show a


loading icon and hide
the comments
https://scotch.io/tutorials/createalaravelandangularsinglepagecommentapplication

37/57

9/20/2015

CreateaLaravelandAngularSinglePageCommentApplication|Scotch

deleteComment():
Well attach this
function to a delete link
so that we can remove
the comment
Now lets get to the actual
code for our view. Well
comment out the main
important parts so we can
see how everything works
together.

https://scotch.io/tutorials/createalaravelandangularsinglepagecommentapplication

38/57

9/20/2015

CreateaLaravelandAngularSinglePageCommentApplication|Scotch

<!app/views/index.php>
<!doctypehtml><htmllang="en"><head><meta
<!CSS>

<linkrel="stylesheet"href="//netdna.bootstrapcdn.com/bootstrap/3.1

<linkrel="stylesheet"href="//netdna.bootstrapcdn.com/fontawesome/
<style>
body{paddingtop:30px;}
form{paddingbottom:20px;
.comment{paddingbottom:20px;
</style>

<!JS>

<scriptsrc="//ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min

<scriptsrc="//ajax.googleapis.com/ajax/libs/angularjs/1.2.8/angular

<!ANGULAR>

<!allangularresourceswillbeloadedfromthe/publicfolder
<scriptsrc="js/controllers/mainCtrl.js
<scriptsrc="js/services/commentService.js
<scriptsrc="js/app.js"></script><!loadourapplication>

</head>
<!declareourangularappandcontroller>
<bodyclass="container"ngapp="commentApp"
<!PAGETITLE===============================================>
<divclass="pageheader">
<h2>LaravelandAngularSinglePageApplication
<h4>CommentingSystem</h4>
</div>

<!NEWCOMMENTFORM==============================================

<formngsubmit="submitComment()"><!ngsubmitwilldisablethed

https://scotch.io/tutorials/createalaravelandangularsinglepagecommentapplication

39/57

9/20/2015

CreateaLaravelandAngularSinglePageCommentApplication|Scotch

<formngsubmit="submitComment()"><!ngsubmitwilldisablethed

<!AUTHOR>
<divclass="formgroup">
<inputtype="text"class="formcontrolinputsm
</div>

<!COMMENTTEXT>
<divclass="formgroup">
<inputtype="text"class="formcontrolinputlg
</div>

<!SUBMITBUTTON>
<divclass="formgrouptextright">
<buttontype="submit"class="btnbtnprimarybtnlg
</div>
</form>

<!LOADINGICON===============================================
<!showloadingiconiftheloadingvariableissettotrue>
<pclass="textcenter"ngshow="loading

<!THECOMMENTS===============================================
<!hidethesecommentsiftheloadingvariableistrue>
<divclass="comment"nghide="loading"
<h3>Comment#{{comment.id}}<small
<p>{{comment.text}}</p>

<p><ahref="#"ngclick="deleteComment(comment.id)
</div>

</div>
</body>
</html>

https://scotch.io/tutorials/createalaravelandangularsinglepagecommentapplication

40/57

9/20/2015

CreateaLaravelandAngularSinglePageCommentApplication|Scotch

(https://cask.scotch.io/2014/
02/laravel-angular-singlepage-application1.jpg)
Now we finally have our
view that brings all of the
parts we created together.
You can go ahead and play
around with the application.
All the parts should fit
together nicely and creating
and deleting comments
should be done without a
page refresh.

Testing the
Application
https://scotch.io/tutorials/createalaravelandangularsinglepagecommentapplication

41/57

9/20/2015

CreateaLaravelandAngularSinglePageCommentApplication|Scotch

Make sure you take a look at


the Github repo
(https://github.com/scotchio/laravel-angular-commentapp) to test the application.
Here are some quick
instructions to get you
going.
1. Clone the repo: git
clone
git@github.com:scotch
io/laravelangular
commentapp

2. Install Laravel: composer


installpreferdist

3. Change your database


settings in
app/config/database.ph
p

4. Migrate your database:


phpartisanmigrate

5. Seed your database:


phpartisandb:seed

6. View your application in


the browser!

Conclusion

https://scotch.io/tutorials/createalaravelandangularsinglepagecommentapplication

42/57

9/20/2015

CreateaLaravelandAngularSinglePageCommentApplication|Scotch

Conclusion
Hopefully this tutorial gives
a good overview of how to
start an application using
Laravel and Angular. You
can bring this farther and
create a full application that
can handle multiple API calls
on the Laravel side, and
even create your own
Angular routing
(https://scotch.io/tutorials/ja
vascript/single-page-appswith-angularjs-routing-andtemplating) for multiple
pages.
Sound off in the comments
if you have any questions or
would like to see a specific
use case. We can also
expand on this demo and
start adding different things
like editing a comment, user
profiles, whatever.
https://scotch.io/tutorials/createalaravelandangularsinglepagecommentapplication

43/57

9/20/2015

CreateaLaravelandAngularSinglePageCommentApplication|Scotch

VIEW CODE
(HTTPS://GITHUB.COM/SCOTCHIO/LARAVEL-ANGULARCOMMENT-APP)

(https://scotch.io/author/chris)

CHRIS SEVILLEJA
(HTTPS://SCOTCH.IO/AUTHOR/CHRIS)
(@SEVILAYHA
(HTTPS://TWITTER.COM/SEVILAYHA))
https://scotch.io/tutorials/createalaravelandangularsinglepagecommentapplication

44/57

9/20/2015

CreateaLaravelandAngularSinglePageCommentApplication|Scotch

Design, development, and


anything in between that I find
interesting.
View My Articles (https://scotch.io/author/chris)

READ NEXT
(https://scotch.io/tutorials/setting(https://scotch.io/tutorials/creatingup-a-mean-

a-single-page-

stack-single-

todo-app-

page-

with-node-

application)

and-angular)

SETTING UP
CREATING A
A MEAN
SINGLE PAGE
STACK
TODO APP
SINGLE PAGE
WITH NODE
APPLICATION
AND
(HTTPS://SCOTCH.IO/TUTORIALS/SETTINGANGULAR
UP-A-MEAN(HTTPS://SCOTCH.IO/TUTORIALS/CREATINGSTACKA-SINGLESINGLEPAGE-TODOPAGEAPP-WITHAPPLICATION)
NODE-ANDANGULAR)

(https://scotch.io/tutorials/node(https://scotch.io/tutorials/singleand-angular-

https://scotch.io/tutorials/createalaravelandangularsinglepagecommentapplication

45/57

9/20/2015

and-angular-

CreateaLaravelandAngularSinglePageCommentApplication|Scotch

to-do-appapplicationorganization-

page-appswithangularjs-

NODE AND
SINGLE PAGE
ANGULAR
APPS WITH
TO-DO APP:
ANGULARJS
APPLICATION
ROUTING
ORGANIZATION
AND
AND
TEMPLATING
STRUCTURE
(HTTPS://SCOTCH.IO/TUTORIALS/SINGLE(HTTPS://SCOTCH.IO/TUTORIALS/NODEPAGE-APPSANDWITHANGULARANGULARJSTO-DO-APPROUTINGAPPLICATIONANDORGANIZATIONTEMPLATING)
ANDSTRUCTURE)

(https://scotch.io/tutorials/understanding(https://scotch.io/tutorials/simplelaravel-route-

and-easy-

parameters)

laravel-loginauthentication)

UNDERSTANDING
SIMPLE AND
LARAVEL
EASY
ROUTE
LARAVEL
PARAMETERS
LOGIN
(HTTPS://SCOTCH.IO/TUTORIALS/UNDERSTANDINGAUTHENTICATION
LARAVEL(HTTPS://SCOTCH.IO/TUTORIALS/SIMPLEROUTEAND-EASYPARAMETERS)
LARAVELLOGINAUTHENTICATION)

https://scotch.io/tutorials/createalaravelandangularsinglepagecommentapplication

46/57

9/20/2015

CreateaLaravelandAngularSinglePageCommentApplication|Scotch

SUBSCRIBE
FOLLOW LIKE

+1

(HTTPS://SCOTCH.IO/FEED)
(HTTP://TWITTER.COM/SCOTCH_IO)
(HTTP://WWW.FACEBOOK.COM/SCOTCHDEVELOPM
(HTTP://PLUS.GOOGLE.COM/B/113854128

Get valuable tips, articles, and


resources straight to your inbox. Every
Tuesday.
Email Address
Subscribe

Comments

Community

Recommend 3

Login

SortbyBest

Jointhediscussion
twlizard 2yearsago
https://scotch.io/tutorials/createalaravelandangularsinglepagecommentapplication

47/57

9/20/2015

CreateaLaravelandAngularSinglePageCommentApplication|Scotch

twlizard 2yearsago

greattutorialsofar!justonequestion,Iused
yourcodefortheroutesbutwhenIcheckmy
routesfromthecommandlineIdon'thavea
rowforapi.comments.show.Iwasn'texpecting
tohavethatroutesincewedidn'tcreatea
showcontrollerbutyouhavethatroute
availableinyourscreenshot.Shouldtherebea
showcontroller?IstheresomethingI'm
missing?
22

Reply Share

DavidKnight ayearago

Onsubmitanddestroysuccess,youdon't
needtorefreshthecommentlistusing.get(),
youshouldsimply$scope.comments.push(
$scope.commentData)and
$scope.comments.splice(index,1)where
indexispassedintothedestroyfunctionasa
parameter.Thiswouldsaveyoutwoadditional
XHRrequestsandunnecessarywaitandload
time.
6

Reply Share

Hasan>DavidKnight ayearago

No,youcannotdothat,becozithasto
communicatewithrestapiallthetime.If
youpushit,it'llpushcommentwithout
commentID,sothedeletefunction
wouldnotworkwithoutcommentid.
AndI'mnotsurewhyspliceisnot
working:/
1

Reply Share

Guest>Hasan
ayearago

I'manoobinAngularJS,andI
juststartedtolearnthisfw,butI
thinkthatyouarenotrighthere.
Ithinkyoueasilycan
add\removeacommentwithout
usingextracallof
`Comment.get()`justbecause
youuseAPI.Andhowweall

https://scotch.io/tutorials/createalaravelandangularsinglepagecommentapplication

48/57

9/20/2015

CreateaLaravelandAngularSinglePageCommentApplication|Scotch

youuseAPI.Andhowweall
know,agoodAPIallthetime
musttoreturnallneededinfo
aboutnewcreatedrecord,likea
response,andexactlythisinfo
wecanuseto`push`thenew
recordinour`commentData`.
Sorryformyenglish!
Cheers!
1

Reply Share

Jaimin ayearago

Thisisthebesttutorialforangularjsand
laravel.Iwanteditcommentlinksothatyou
caneditcommentandupdateitindatabase.
Hasanyoneusedorimplementedupdatecode
forthisone?
5

Reply Share

Kevin ayearago

ThankyoufortheGreatTutorial!Onequestion
ishowIcaninjecttheCSRFtokeninAngular
andhandlesitbyLaravel?
3

Reply Share

ChrisSevilleja
ayearago

Bartender >Kevin

Heysorryforthelateresponse.Laravel
keepsatokeninSessionthatyoucan
grabwithSession::token().Youcould
useAngulartorequestatokenwhen
creatingaformandthenbindthattoa
variableforwhenyousendthePOST.
Thecsrftokenwouldtreatthatthe
sameasanormalPOST.

Reply Share

Jaimin ayearago

Hasanyoneaddedpaginationincommentsto
paginateusingthistutorial?
2

Reply Share

NickSalloum>Jaimin
8monthsago

https://scotch.io/tutorials/createalaravelandangularsinglepagecommentapplication

49/57

9/20/2015

CreateaLaravelandAngularSinglePageCommentApplication|Scotch

8monthsago

Haven'tdoneso,butlaraveldoesmake
paginationeasy.Here'sthedocsforit
http://laravel.com/docs/4.2/pa...might
beaneasyimplementation?

Reply Share

Alex 2yearsago

Thanksforthatnicelittletutorial.Itallworked
straightaway(veryrarewithme)andiam
nowinspiredtocontinuedigginginthat
direction.Cheersandkeepupthegoodwork.
2

Reply Share

waseemmachloy 2yearsago

whatisbenefitforusingangular,jsinthis
commentsystem.:)justcuriousabout
angula.jsbenefit
2

Reply Share

ChrisSevilleja Bartender >


waseemmachloy 2yearsago

Thisexampledoesn'tfullyshowthe
powerthatAngularcanprovideinthis
setup.HandlingtheAJAXcallsinan
Angularserviceandhavingseparated
codeoutintocontrollersletsusexpand
ourappeasierthanifwewerecreating
thiswithjustjQuery.
Sincetheserviceandcontrollerare
separateandmodular,wecanrununit
testsonourapptomakesurethat
everythingworksaccordingtoplan.
Whilethisdoesn'tshowtoomuchofthe
benefits,whenyouwanttobuildalarger
application,itcanhelpgreatlyfor
testability,scalabilityofcode,and
handlingthefrontenddataissomuch
easier.
2

Reply Share

JeroenKnockaert amonthago

Ihavefollowedeverysinglestepinthistutorial
andi'mgettingthiserror:
https://scotch.io/tutorials/createalaravelandangularsinglepagecommentapplication

50/57

9/20/2015

CreateaLaravelandAngularSinglePageCommentApplication|Scotch

andi'mgettingthiserror:
"Useofundefinedconstantcomment
assumed'comment'"
HowcanIfixthis?
1

Reply Share

Sam>JeroenKnockaert
23daysago

Ihavethesameproblem.Didyoufigure
outwhatitis?

Reply Share

JeroenKnockaert>Sam
20daysago

I'mnotsureifmysolutionwas
therightwaytosolvethis,I
typed'@'beforeeveryvariable.
Forexample:@{{comment.id}}
insteadof{{comment.id}}
Thissolvedtheproblemforme
1

Reply Share

Sam>Jeroen
Knockaert
15daysago

Thanks!Thatworked.

Reply

Share

FlorianZemke 7monthsago

IcreatedaLaravel5andAngularJSstarter
boilerplateprojectgettingyoustartedwiththe
newLaravel5andAngularJSwithautomated
routingandmanyfeaturesthatwillgetyou
startedquickly.
https://github.com/Zemke/start...
1

Reply Share

FlorianZemke>FlorianZemke
5monthsago

Authenticationhasbeenadded.

Reply Share

Guest>FlorianZemke
6monthsago

well,igotthiserror
ErrorExceptioninhelpers.phpline

https://scotch.io/tutorials/createalaravelandangularsinglepagecommentapplication

51/57

9/20/2015

CreateaLaravelandAngularSinglePageCommentApplication|Scotch

ErrorExceptioninhelpers.phpline
619:file_get_contents(/home/chabib/Code/starter
laravelangular/public/build/rev
manifest.json):failedtoopenstream:
Nosuchfileordirectory(View:
/home/chabib/Code/starterlaravel
angular/resources/views/layout.blade.php)

Reply Share

FlorianZemke>Guest
6monthsago

Hey,thankyoufortryingoutthe
project!Pleasefollowthe
installationinstructionsinthe
readme.Runningthecommands
willfixyourproblem.Running
`gulp`shouldfixyourproblem.
Havefun!
https://github.com/Zemke/start...

Reply Share

Guest>FlorianZemke
6monthsago

sweet,thisiswhatiamlookingfor
thanks

Reply Share

FlorianZemke>Guest
6monthsago

Happytohearthis!Ifyouhave
anysuggestions,questionsor
something,pleasereachoutto
meoropenanissue.Havefun!

Reply Share

Samfrombtheeuwes.com ayearago

Pleasenotetomakethedeletefunctionwork,
intheHTMLcode,use:
Delete
Note'datangclick'.Thanksforthetutorial!
1

Reply Share

DaveRev ayearago

Hi!Greatapp,it'salsoveryusefulto
understandandtestangularwithlaravel!
https://scotch.io/tutorials/createalaravelandangularsinglepagecommentapplication

52/57

9/20/2015

CreateaLaravelandAngularSinglePageCommentApplication|Scotch

understandandtestangularwithlaravel!
I'mtryingtoimplementalsotheupdatemethod,
inlaravelandinangularservice,butIcan'tget
itworking!Canyouhelpmeplease?Ialso
haveabitbucketrepowithallmytests.
Thanks!
*Edit:isolved!:)
1

Reply Share

RubenKuipers>DaveRev
7monthsago

Canyoutellmehowyoudidit?I'm
currentlytryingtoimplementthatupdate
featuremyself,butIcan'treallygetmy
headaroundit.

Reply Share

EricLeroy 2yearsago

GreattutorialbutIalwaysgetthesameissue:
GEThttp://localhost:8888/api/comments404
(NotFound)
Unabletoviewexistingcomments.Thesame
whentryingtosaveacomment
Anyidea?
1

Reply Share

ChrisSevilleja Bartender >Eric


Leroy 2yearsago

Fromyourcommandline,whenyou
typephpartisanrouteswhatroutesdo
yousee?
1

Reply Share

EricLeroy>ChrisSevilleja
2yearsago

Thesameasyou:
++
++
++
+
|Domain|URI|Name|Action|
BeforeFilters|AfterFilters|
https://scotch.io/tutorials/createalaravelandangularsinglepagecommentapplication

53/57

9/20/2015

CreateaLaravelandAngularSinglePageCommentApplication|Scotch

BeforeFilters|AfterFilters|
++
++
++
+
||GET/||Closure|||
||GETapi/comments|
api.comments.index|
CommentController@index|||
||POSTapi/comments|
api.comments.store|
CommentController@store|||
||GET
api/comments/{comments}|
api.comments.show|
CommentController@show|||
||DELETE
api/comments/{comments}|
api.comments.destroy|
CommentController@destroy||
|
PleasenotethatI'musing
MAMPandthattherootfolderis
localhost:8888/myapp/public(as
forallLaravelapps).
++
++
++
+
1

Reply Share

ChrisSevilleja
Bartender >Eric
Leroy 2yearsago

Whenyoudo
Comment.get(),addan
errorintheresoyoucan
seeifanerrorcomes
backintheconsole.
https://scotch.io/tutorials/createalaravelandangularsinglepagecommentapplication

54/57

9/20/2015

CreateaLaravelandAngularSinglePageCommentApplication|Scotch

Comment.get()

.success(function(data){

$scope.comments=data;

$scope.loading=false;

})

.error(function(data){
console.log(data);
});

Also,canyougotothe
routedirectlyinthe
browser?
http://localhost:8888/myapp/public
1

Reply

Share

EricLeroy>Chris
Sevilleja
2yearsago

Trappingerror:nothing
intheconsole.
With:
http://localhost:8888/larang/public/api/comments
Igetthejson:
[{"id":"1","text":"LookIam
atest
comment.","author":"Chris
Sevilleja","created_at":"2014
0212
22:40:17","updated_at":"2014
021222:40:17"},
{"id":"2","text":"Thisis
goingtobesuper
crazy.","author":"Nick
Cerminara","created_at":"2014
0212
22:40:17","updated_at":"2014
021222:40:17"},
{"id":"3","text":"Iama
masterofLaraveland
Angular.","author":"Holly
Lloyd","created_at":"2014
0212
https://scotch.io/tutorials/createalaravelandangularsinglepagecommentapplication

55/57

9/20/2015

CreateaLaravelandAngularSinglePageCommentApplication|Scotch

0212
22:40:17","updated_at":"2014
021222:40:17"}]
Itisasif
CommentService.jswas
notcalledordidnotcall
routes.php
1

Reply

Share

ChrisSevilleja
Bartender >Eric
Leroy 2yearsago

IfthatistheURLyou
seedataat,thenusethat
URLinyour
CommentService.Since
therearenoconsole
errorsthentherearen't
anyerrorsloadingupthe
CommentService.
Tryusingthe
/larang/public/api/comments
astheURL.
1

Reply

(https://www.facebook.com/scotchdevelopment)
(https://twitter.com/scotch_io)
(https://plus.google.com/+ScotchIo/posts)
(http://feeds.feedblitz.com/scotch_io)

License (/license)
Advertise with Us (/advertise)
About (/about)
Join Us on Slack (https://scotch-slack.herokuapp.com/)
Store (http://shop.scotch.io)
https://scotch.io/tutorials/createalaravelandangularsinglepagecommentapplication

56/57

9/20/2015

CreateaLaravelandAngularSinglePageCommentApplication|Scotch

Write for Us (/write-for-us)


Contact Us (/contact-us)
JOIN THE NEWSLETTER
Web design/development tutorials and news from around the web.
Email Address
Subscribe

Hire Us (http://bit.ly/18ib8jR)

(https://leanpub.com/mean-machine)

LEARN NODE AND ANGULAR


Scotch's new JavaScript eBook. Learn the full JavaScript stack.
Get the Book (https://leanpub.com/mean-machine)

Web design and development tutorials for the masses.


Scotch.io | Proudly hosted by Digital Ocean (https://www.digitalocean.com/?
refcode=eaf67777e85b)

https://scotch.io/tutorials/createalaravelandangularsinglepagecommentapplication

57/57

Anda mungkin juga menyukai