Using the Laravel Dingoapi plugin

Source: Internet
Author: User

Dingoapi is a laravel open source plugin that can be found on GitHub and is now working on a project where there is always a JSON data interaction at the front end of the backend, and this dingoapi provides a great convenience for JSON interaction.

Install Dingoapi First

1. Add "Dingo/api": "1.0.* @dev" in require in Composer.json and run composer update at the project root directory.

Note : Dingoapi if installed directly with composer require dingo/api:[email protected] is not installed successfully,

Because the package author himself or set it as a development, non-stable version, but in fact the package has been verified to be stable, has 4500+ star.

2, registered service provider in config/app.php to providers

Dingo\api\provider\laravelserviceprovider::class,

3. Generate DINGOAPI configuration file

PHP artisan vendor:publish--provider= "Dingo\api\provider\laravelserviceprovider"

This configuration file will be generated in the Config folder api.php

4, the prefix default value in api.php is set to the API, it may not be the API, but must have a suffix, the suffix is not set to "/", if set to "/", Laravel View and API will be confused, for example, A 404 error page has been customized in Laravel, and if this is set to "/", the error message formatted as JSON is returned when the page is not present, because DINGAPI is used for the interface, no matter what will be converted to JSON.

If you want to distinguish the view from the API, the routing file needs to be written like this, here is an example:

<?PHP/*|--------------------------------------------------------------------------| Web routes|--------------------------------------------------------------------------| | This file is where you may define all of the routes it is handled| By your application. Just tell Laravel the URIs it should respond| To using a Closure or controller method. Build something great!|*/Route::p ost ('/test ', ' [email protected] '); Route::p ost ('/hook ', ' [email protected] ');#Background Management System login ViewRoute::get ('/admin ', ' [email protected] '); Route:: Get ('/admin/login ', ' [email protected] ');#Background Management System login APIRoute::p ost ('/admin/login ', ' [email protected] ');#Sign out of the login APIRoute::get ('/logout ', ' [email protected] ');#Administrator Visible ViewRoute::group ([' Middleware ' = [' role:admin ']],function () {    #User List ViewRoute::get ('/users ', ' [email protected] '); #Add user ViewRoute::get ('/add_user ', ' [email protected] '); #Mechanic List ViewRoute::get ('/mechanics_list ', ' [email protected] '); #Accessories List ViewRoute::get ('/parts_list ', ' [email protected] '); #Add an accessory viewRoute::get ('/add_part ', ' [email protected] '); Route:: Match ([' Get ', ' post '], '/mechanics_add ', ' [email protected] '); Route:: Get ('/edit_user/{id} ', ' [email protected] '); Route:: Get ('/video ',function(){        returnView (' Video ', [' title ' = ' + ']); });});$api= App (' Dingo\api\routing\router ');$api->version (' v1 ',function($api) {    $api->group ([' namespace ' = ' App\http\controllers\api '),function($api) {
namespace declares the namespace of the routing group, because the "prefix" + "API" is set above, so the following routes have an API prefix, such as request/api/users_list to access the user list interface$api->group ([' Middleware ' =>[' role:admin '],function($api) { #administrator-Available interfaces #User List API $api->get ('/users_list ', ' [email protected] '); #Add User API $api->post ('/add_user ', ' [email protected] '); #Edit User API $api->post ('/edit_user ', ' [email protected] '); #Delete User API $api->post ('/del_user ', ' [email protected] '); #Upload Avatar API $api->post ('/upload_avatar ', ' [email protected] '); }); });});

You need to create a new Basecontroller:

<? phpnamespace App\http\controllers\api;  Use dingo\api\routing\helpers;  Use App\http\controllers\controller; class extends controller{    use  Helpers;}

And then the controller that does the interface inherits this Basecontroller

These are the interfaces that the controller puts in the API folder

Then if the use of requests for verification, the original request should be used illuminate\foundation\http\formrequest replaced with use dingo\api\http\formrequest;

Otherwise, the message of the validation error cannot be explicitly displayed.

Here are some of the features I used to DINGOAPI:

First feature:

When I use jquery's AJAX request server data, Ajax actually has two parameters, success callback function and error callback function, in Laravel, if I directly return response to an array, The Laravel framework automatically turns this array into a JSON-formatted response, so I write code similar to the following in the Laravel code:

if    ($error) {    return [' status ' = ' error ', ' = ' + ' message ' = ' failed verification ']; // returns a 200 response code, but returns the identity of status error      }return [' status ' = ' success ', ' = ' + ' message ' = ' operation succeeded ']; // returns a 200 response code, and returns the identity of status success

This time the success callback function of the front-end jquery can determine the success of the operation based on the status identity:

DataType: ' JSON ', // Note here to write JSON, the identity server returned is Json,jquery will convert the JSON string into a JSON object for easy access to the data success:     function(res) {     if(res.status = = ' ERROR ') {alert (res.message);    // This will alert a "failed validation"  }  else{alert (res.message);  // This will alert a "successful operation"  }}

This is a front-end and back-end method of passing data, regardless of whether the operation succeeds or fails to return 200 of the correct response, according to status to determine the operation success or failure.

If I use Dingoapi, DINGOAPI can return both the exception and the JSON data (if you don't use DINGOAPI, returning an exception will return an HTML page of the exception).

So you can use jquery's Ajax error callback function to confirm the behavior of the failed operation:

Datatype:json,

Error:function (Error) {

Alert ($.parsejson (Error.responsetext)); The Parsejson method converts a JSON string into a JSON object

}

here is a method in the Laravel controller.

        Here is the AJAX error callback function

This is the browser's console.


After reading the effect to know why to use Parsejson to convert the JSON string into a JSON object, because the ResponseText property is a JSON-formatted string, but not an object.

Converting to an object will later output an error message.

Second function:

Using Dingoapi's Tranform

Create a new usertransformer.php file under app\http\transformers (This Transformers folder is also new):

<?phpnamespace app\http\transformers; UseApp\models\user; Useleague\fractal\transformerabstract;classUsertransformerextendstransformerabstract{protected $availableIncludes= []; protected $defaultIncludes= [];  Public functionTransform (User$item)    {        return [                ' id ' =$item->id, ' name ' = =$item->name, ' sex ' =$item->sex, ' telphone ' =$item->telphone, ' car_company ' =isset($item->car->car_company)?$item->car->car_company: ', ' license_plate ' =isset($item->car->license_plate)?$item->car->license_plate: ', ' birthday ' =$item->birthday, ' created_at ' = (string)$item->created_at, ' first_time ' =isset($item->car->first_time)?$item->car->first_time: ', ' integral ' =$item->integral,        ]; }}

After this definition, in the control

<?php

namespace App\http\controllers\api;

Use App\models\user;

Use App\http\transformers\usertransformer;

Class Userapicontroller extends Basecontroller//here Inherit Basecontroller

{

Public Function users () {

    $user->all ();    Here you can also write some where condition    return $this->response->item ($user, new Usertransformer);

}

}

This will be all the other fields in the $user filter out, so the words are very normative, the controller does not have to write too much data conversion.

Of course, if you want to implement filter arrays in control, you can use the following common functions:

Array_filter ($arr)

parameter is an array that implements an array element with a null filter key value

The array_only ($arr) parameter is an array that retains only the keys in the parameter array, and all the rest is filtered out

The array_except ($arr) parameter is an array, except for the keys outside the parameter array, all of the rest are filtered out

Of course, Dingoapi's function is certainly not only these two, there are many, I will slowly in use to take notes.

Using the Laravel Dingoapi plugin

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.