Ways to implement single-page comments using Angularjs and PHP laravel

Source: Internet
Author: User
Tags php class composer install laravel migration
This article mainly describes the use of Angularjs and PHP laravel implementation of single-page comments, the example of this article is the front-end JavaScript and back-end PHP joint programming model, the need for friends can refer to the following

At present, laravel and angular have become very famous tools in the world of web development. Laravel is known for the great content introduced by the PHP community, and angular is known for its amazing front-end tools and simplicity. The combination of these two frameworks seems to be the logical next step.

In our usage environment, we will use Laravel as the backend restful api,angular as the front end to create a simple one-page comment application.

Here's a simple example that shows how to get started with these two technologies, so don't be afraid of what extra database stuff is, how to deal with sub-comments or whatever.

What we will create

This will be a simple one-page comment application:

    • RESTful Laravel API handles getting, creating, and deleting comments;

    • The angular frontend is responsible for displaying the forms and comments we created;

    • Be able to create a new comment and add it to our w/o page refresh list;

    • The ability to delete a comment and remove it from the w/o page refresh list.

In general, these are very simple concepts. Our focus is on the intricate relationship between how laravel and angular work together.

Laravel back end
Set Laravel

Continue to set up your laravel, we will do some basic work to make our back-end implementation of comments and additions and deletions to change:

    • Create a Database migration

    • Inserting sample comments into a database

    • Create a routing table for our API

    • Create a "Get all" routing table to let angular out of the route

    • Create a resource controller for comments

Prepare for database migration

We want a simple structure that stores comments and only includes content and authors. Let's create a laravel migration to create a comment.

Let's run the artisan command to create a comment migration so that we can build a comment table in our database:

  PHP Artisan migrate:make create_comments_table--create=comments

We will use the Laravel schema Builder to create the required content and author fields. Laravel also creates IDs and timestamps columns so that we can know when the comment was added. Here is the code for the comment form:

app/database/migrations/####&# #_ ##### #_create_comments_table. php   ... /**   * Run the migrations.   *   * @return void */public  function up ()  {    schema::create (' Comments ', function (Blueprint $table)    {      $table->increments (' id ');       $table->string (' text ');      $table->string (' author ');       $table->timestamps ();    });  } ...

Make sure you have adjusted the database settings with the correct credentials in the "app/config/database.php" file. Now let's run the migration so that we can create this table with the required columns:

  PHP Artisan Migrate

Comment Model

We will use the Laravel eloquent model to interact with the database. This is easy to do, let's create a model: "app/models/comment.php":

<?php//app/models/comment.php class Comment extends eloquent {    /let eloquent know that these attributes would be Available for mass assignment  protected $fillable = Array (' Author ', ' Text ');}

Now that you have the table and the model, let's add a sample data to the table by Laravel seeding.
Seeding Database

We need some comments to test a few things. Let's create a seed file and insert a three sample comment into the database.

Create a file: "app/database/seeds/commenttableseeder.php" and add the following code:

<?php//app/database/seeds/commenttableseeder.php class Commenttableseeder extends Seeder {public   function run ()  {    db::table (' comments ')->delete ();     Comment::create (Array (      ' author ' = ' Chris sevilleja ',      ' text ' + ' look I am a test Comment. '    ));     Comment::create (Array (      ' author ' = ' Nick Cerminara ',      ' text ' = ' = ' This was going to be super crazy. '    ));     comment::create (Array (      ' author ' = ' Holly Lloyd ',      ' text ' = ' I am a master of Laravel and Angular. '    ));  } }

To invoke this planter file, we will modify "app/database/seeds/databaseseeder.php" and add the following code:

     app/database/seeds/databaseseeder.php ... /**   * Run the database seeds.   *   * @return void */public  function run ()  {    eloquent::unguard ();     $this->call (' Commenttableseeder ');    $this->command->info (' Comment table seeded. ');  } ...

Now we run our seeder with the artisan command.

PHP Artisan Db:seed

Now we have a database with a comment table, a eloquent model, and some database samples. It's not a bad day's work ... But we are far from over.

Comment Resource Controller (app/controllers/commentcontroller.php)

We will use the Laravel resource controller to process the comment API functions. Because you use angular to display a resource and create and update forms, we will create a resource controller with the artisan command without creating and editing functions.

Let's create a resource controller with artisan.

  PHP Artisan controller:make Commentcontroller--only=index,store,destroy

For the example application, we will only use these three functions in the resource controller. To extend, you need to include all functions such as updating, displaying, etc. to achieve a more mature application.

We've created the controller, so we don't need to create and edit functions, because angular, not laravel, handles the work of displaying the form. The Laravel is only responsible for returning the data to the front end. In order to make things simple, we have also proposed an update function from the instance application. We'll deal with creating, displaying, and deleting comments.

To return the data, we want the data to be returned in JSON form. Let's take a look at the new controller and add the appropriate function.

<?php//app/controllers/commentcontroller.php class Commentcontroller extends \basecontroller {   /**   * Send Back all comments as JSON   *   * @return Response   *  /Public Function index ()  {    return Response:: JSON (Comment::get ());  }   /**   * Store A newly created resource in storage.   *   * @return Response */public  function store ()  {    comment::create (      ' Author ' = > Input::get (' Author '),      ' text ' = + input::get (' text '))    ;     return Response::json (Array (' success ' = True);  }   /**   * Remove The specified resource from storage.   *   * @param int $id   * @return Response   *  /Public Function Destroy ($id)  {    Comment:: Destroy ($id);     return Response::json (Array (' success ' = True);  } }

You can see how easy it is to use laravel and eloquent to handle additions and deletions. It's incredibly easy to deal with the functions we need.

As the controller is ready to complete, one of the last things we need to do at the back end is routing.

Our routing table (app/routes.php)

As the database is ready, let's deal with the routing table for the Laravel application. Now that it has its own route, we'll use the routing table to send the data to the front end. We also provide a routing table to the backend API so that people can access our comment data.

Let's create a angular point to the routing table. We need a home page routing table and a "Get all" routing table that sends users to angular. This ensures that users can access our web site regardless of how they are routed to the angular front end.

We will take a ... (please drum) ... API as API routing table prefix. In this way, if someone wants to get all the comments, they will use the URL. This is just a good strategy for moving forward and some basic API creation.

<?php//app/routes.php//=============================================//HOME PAGE ============================= ======//=============================================route::get ('/', function () {//We dont need to use Laravel Blade/ /We'll return a PHP file that would hold any of our Angular content//See the ' Where to place Angular Files ' below to See Ideas structure your app return View::make (' index '); would return app/views/index.php}); =============================================//API ROUTES ==================================//================ =============================route::group (Array (' prefix ' + ' API '), function () {////Since we'll be the using this just For CRUD, we won ' t need create and edit//Angular would handle both of those forms//This ensures that a user can ' t acc ESS Api/create or Api/edit when there's nothing there Route::resource (' comments ', ' Commentcontroller ', Array (' only ' = > Array (' Index ', ' Store ', ' destroy ')); // =============================================//CATCH all ROUTE =============================//======================= ======================//all routes that is not home or API would be is redirected to the frontend//this allows angular to r Oute themapp::missing (function ($exception) {return view::make (' Index ');});

We now have a routing table to handle the three main things laravel to do.

Processing the Get all routing table: in Laravel, you can do this in several ways. In general, it is not ideal to use the above code and get "get all" for the entire application. Alternatively, you can use the Lost method of the Laravel controller to get the routing table.

Testing all the routing tables allows us to ensure that the required routing tables are available. We'll use artisan to see all the routing tables:

  PHP Artisan Routes

This command lets us see all the routing tables and a top-down view of the application.

From we can see the HTTP verb and get all the comments, get, create and destroy a comment on the routing table. At the top of the API routing table, you can see how a user is routed to angular through the Home page routing table.

Background finish

Finally! The backend of our Laravel API has also been completed. We've done a lot, but we have a lot of work to do. We've built and seeded databases, created models and controllers, and built routing tables. We will continue to work on the angular front end.

Where to put the angular file

I have seen this question many times. Where should I put the angular file, and how to make laravel and angular work together.
Let angular handle the front end, we need laravel to direct the user to the index.php file. We can put it in a couple of different places. By default, when you use:

App/routes.phproute::get ('/', function () {   return View::make (' index ');   });

This will return app/views/index.php. Laravel is found by default in the App/views folder.

Some people want to completely separate the angular files from the laravel files. They want their entire application to be placed in the public folder. This is simple: just set the default view location to the public folder. You can complete the setup by modifying the app/config/view.php file.

     app/config/view.php ... Make Laravel look in public/views for view files  ' paths ' = = Array (__dir__. ' /.. /.. /public/views '), ...

Now, return View::make (' index ') will look for the public/views/index.php file. You can fully configure how you want to organize your app. Some people think that the benefits of putting the entire angular application in the public folder are much better, so that routing can be easily handled and, if necessary, completely distinguishable from the backend's restful API and the front-end angular.

In order for angular to be able to route, some of your files need to be placed in the public folder, but this is beyond the scope of this article.

Let's assume that everything is used by default, and our main view file is in our App/views folder, and then we continue.

Using Laravel and angular routes can cause a lot of problems if you use laravel and angular routing conflicts. Laravel will take control of your application as the main route. Angular routing only happens when Laravel routes our users, to Angular main route (index.php) this situation. That's why we use Laravel to control all the routes. Laravel will process the API route and send any unsolicited requests to angular. You can then set up all the routes for your angular app to handle different views.

Front-end angular
Prepare our Application

Every thing in our angular program is handled in the public folder. This can help us to distinguish it from the files in the Backend app folder very well.

Let's take a look at the organizational structure in our public folder. We have created a modular angular program because this is a best practice. Now, the various parts of our program are easy to test and process.

    • -public/

    • -----js/

    • ----------controllers///Where we'll put our angular controllers

    • ---------------Mainctrl.js

    • ----------services///Angular Services

    • ---------------Commentservice.js

    • ----------App.js

Angular Service Public/js/services/commentservice.js

Our angular service is a primary location for us to call the Laravel API via HTTP. It's very easy to understand and we use the Angular $http service.

Public/js/services/commentservice.jsangular.module (' Commentservice ', [])   . Factory (' Comment ', function ($ HTTP) {     return {      //Get all Comments      get:function () {        return $http. Get ('/api/comments ');      },
  //Save a comment (pass in comment data)      save:function (commentdata) {        return $http ({          method: ' POST '),          URL: '/api/comments ',          headers: {' content-type ': ' application/x-www-form-urlencoded '},          data: $.param ( commentdata)        });      },       //Destroy a comment      destroy:function (id) {        return $http. Delete ('/api/ comments/' + ID);}}   );

This is our angular service, which contains 3 different functions. These are the only functions we need because they will correspond to the routing APIs in our laravel.

Our service will return a Promise object. These will be used to handle our controllers. The naming convention here is also consistent with our Laravel controller.

Complete our angular service, let's get started with our controller and use it.

Angular controller Public/js/controllers/mainctrl.js

The controller realizes most of the functions of our application. Here we create functions that handle submitting forms and deleting comments.

Public/js/controllers/mainctrl.jsangular.module (' Mainctrl ', [])//In controller such as Comment Service. Controller (' Maincontroller '     , function ($scope, $http, Comment) {//The object that holds new comments on all form data $scope. Commentdata = {};     Call the variable $scope that displays the load icon. Loading = true; Get all the comments first, then bind them to the $scope.comments object//Use the function defined in the service//Get all COMMENTS ============================================        ======== Comment.get (). Success (function (data) {$scope. comments = data;      $scope. loading = false;     }); function to process the submitted form//SAVE A COMMENT ====================================================== $scope. submitcomment = Functio       N () {$scope. loading = true; Save the comment. Pass a comment in the form room//Use the function created in the service Comment.save ($scope. Commentdata). Success (function data) {///If successful, we need to              Refresh Comment List Comment.get (). Success (function (GetData) {$scope. comments = GetData;            $scope. loading = false;         }); }). Error (function (data) {console.log (data);    });     }; function to process Delete comment//delete A COMMENT ==================================================== $scope. deletecomment = Functio        N (ID) {$scope. loading = true; Use the function Comment.destroy (ID) created in the service. Success (data) {//If successful, we need to refresh the list of comments Comment.get              (). Success (function (GetData) {$scope. comments = GetData;            $scope. loading = false;         });    });   }; });

As you can see in the controller, we have injected the comment service and used it to implement the main functions: GET, save and delete. Use such a service to avoid polluting our controllers with $http get or put.

Connect to our app Public/js/app.js

In terms of angular, we have created services and controllers. Now let's connect together so that we can use Ng-app and ng-controller to apply it to our applications.

This is the code that creates the angular app. We will inject the service and the controller. This is a best practice approach, which enables our applications to be modular, and the various parts are measurable and extensible.

Public/js/app.jsvar Commentapp = angular.module (' Commentapp ', [' Mainctrl ', ' Commentservice ']);

That's it, there's not much work. Now that we have actually achieved our point of view, we can see how the various parts of angular work together.

Our main view app/views/index.php

So far, we're still not able to see anything from the browser after we've done all the prep work. Because Laravel controls our main route, we need to define our view file, and return all routing requests back to return View::make (' index ').

Let's create the view first. We will use all the angular content that we have created. The main part we have created with angular will be the parts we will use primarily in index.php:

    • Ng-app and Ng-controller: apply them by attaching them to the body tag

    • Ng-repeat: Display comments to a template in a loop

    • Submitcomment (): Use Ng-submit to attach this function to the form

    • Loading Icons: We will create a variable called Loading. If it is set to true, we will display a load icon and hide the comment

    • DeleteComment (): We will append this function to a delete link so we can delete the comment

Now let's write the actual code that implements our view. We will comment on the main important parts so that we can see how everything works.

<!--app/views/index.php--><!doctype html>

Now we have finally achieved our point of view, combining all the parts that have been created. You can try this app. All parts should be well combined, and comments should be created and deleted without having to refresh the page.

Test

Make sure you test the Github repo app. Here are the steps to do this process

    • Copy Repo:git clone Git@github.com:scotch-io/laravel-angular-comment-app

    • Installing Laravel:composer Install--prefer-dist

    • Modify Database Connection inapp/config/database.php

    • Data Migration database:php Artisan Migrate

    • Hit the seed database:php artisan db:seed.

    • Browse your App!

Conclusion

In the past this article has helped you with the introduction of using Laravel and angular. Based on this, you can create Laravel apps that use more APIs, and even create your own Angular routing.

The above is the whole content of this article, I hope that everyone's learning has helped, more relevant content please pay attention to topic.alibabacloud.com!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.