×ðÁú¿­Ê±¹ÙÍøµÇ¼

laravelÔõÑùдapi

laravel×÷ΪһÃÅÊ¢ÐеÄphp¿ò¼Ü£¬ÒѾ­³ÉΪÁË¿ª·¢Ö°Ô±Ð´apiµÄÊ×Ñ¡¡£Í¨¹ýlaravel£¬Äã¿ÉÒÔ¿ìËÙ±àд¸ßÖÊÁ¿µÄapi£¬ÆäÔ½À´Ô½Êܵ½ÆóÒµ¼¶ºÍСÎÒ˽ÈË¿ª·¢ÕߵĽӴý¡£

ÔÚÕâƪÎÄÕÂÖУ¬ÎÒÃǽ«Ì½ÌÖÔõÑùʹÓÃLaravel±àдAPI¡£ÎÒÃǽ«´ÓÒÔϼ¸¸ö·½ÃæÈëÊÖ£º¹¹½¨API¡¢API·ÓÉ¡¢¿ØÖÆÆ÷ºÍAPI²âÊÔ¡£

¹¹½¨API

ÔÚ¹¹½¨APIʱ£¬ÐèҪʹÓÃLaravelÌṩµÄÄÚÖÃÖÐÑë¼þºÍ·ÓÉÆ÷¡£´ÓLaravel 5.5×îÏÈ£¬¿ò¼ÜÄÚÖÃÁËAPI×ÊÔ´¿ØÖÆÆ÷£¨API Resource Controller£©¹¦Ð§¡£Õâ¸öÌØÕ÷ʹµÃ¿ª·¢Õß¿ÉÒÔ¸ü¿ìµÄ½¨Éè±ê×¼µÄREST API£¬²¢ÇÒ×ÊÖú¿ª·¢Õßά»¤´úÂëÒ»ÖÂÐÔ¡£

ÔõÑùʹÓÃ×ÊÔ´¿ØÖÆÆ÷£¿Ê×ÏÈ£¬ÔÚÏÂÁîÐÐÖÐÖ´ÐÐÒÔÏÂÏÂÁн¨Ò»¸ö¿ØÖÆÆ÷£º

php artisan make:controller Api/PostController --api

µÇ¼ºó¸´ÖÆ

Õâ»á½¨ÉèÒ»¸öÃûΪPostControllerµÄAPI¿ØÖÆÆ÷£¬Ëü½«×Ô¶¯¼ÌÐøLaravelµÄÄÚÖõÄResourceController£¬²¢ÇÒ°üÀ¨ËùÓеÄÔ¤½ç˵µÄÒªÁì¡£ÕâЩҪÁì°üÀ¨£ºindex¡¢show¡¢store¡¢updateºÍdestroy¡£

API·ÓÉ

ÔÚLaravelÖУ¬Â·ÓÉÓë¿ØÖÆÆ÷ϸÃÜñîºÏ£¬ÓÉÓÚÎÒÃÇÐèÒªÔÚ·ÓÉÖнç˵´¦ÀíAPIÇëÇóµÄ¶¥¼¶¿ØÖÆÆ÷¡£

Route::prefix('api')->group(function () {
    Route::resource('posts', 'Api\PostController');
});

µÇ¼ºó¸´ÖÆ

Õâ¸ö·Óɽç˵ÁËÒ»¸ö’/api/posts’µÄURL£¬ÓÃÀ´²Ù×÷PostÄ£× CRUD ¹¦Ð§¡£

¿ØÖÆÆ÷

ÔÚ×ÊÔ´¿ØÖÆÆ÷ÖУ¬ÎÒÃÇ¿ÉÒÔʹÓÃÔ¤½ç˵µÄº¯ÊýÀ´´¦Àí³£¼ûµÄʹÃü¡£ÀýÈ磬ÏÂÃæµÄ´úÂë×îÏȽ¨Éè²¢¸½¼ÓpostÎÄÕµÄÎļþÉÏ´«£¬½«Îļþ´Ó´æ´¢¿âÖÐÒƶ¯µ½¹«¹²Ä¿Â¼ÖУº

public function store(Request $request)
{
    $path = $request->file('photo')->store('public/photos');
    
    $post = new Post;
    
    $post->title = $request->input('title');
    $post->description = $request->input('description');
    $post->slug = str_slug($request->input('title'));
    $post->photo = $path;
    
    $post->save();
    
    return new Resource($post);
}

µÇ¼ºó¸´ÖÆ

API²âÊÔ

²âÊÔAPIÊÇÈ·±£Æ书ЧÕý³£ÊÂÇéµÄÒªº¦£¬ÇëÈ·±£ÔÚ±àдAPIʱ±àд²âÊÔÓÃÀý¡£LaravelÒ²ÄÚÖÃÁË¿ò¼Ü²âÊÔ¹¤¾ßÀ´×ÊÖúÄúÇáËɵرàд²âÊÔÓÃÀý¡£

ÔÚΪAPI±àд²âÊÔʱ£¬Äú¿ÉÒÔʹÓ÷¢ËÍHTTPÇëÇó²¢¼ì²éÏìÓ¦µÄÒªÁìÀ´²âÊÔ¿ØÖÆÆ÷¡£ÀýÈ磬ÏÂÃæµÄ´úÂë²âÊÔ¿ØÖÆÆ÷ÊÇ·ñ¿ÉÒÔ׼ȷµØ»ñÈ¡Ìû×ÓµÄÁÐ±í£º

public function testPostIndex()
{
    $response = $this->json('GET', '/api/posts');
    
    $response->assertStatus(200);
    $response->assertJsonStructure([
        'data' => [
            '*' => [
                'id',
                'title',
                'description',
                'slug',
                'photo',
                'created_at',
                'updated_at'
            ]
        ]
    ]);
}

µÇ¼ºó¸´ÖÆ

½áÂÛ

ÔÚLaravelÖУ¬±àдAPIºÜÊÇÈÝÒס£Ê¹ÓÃÔ¤½ç˵µÄAPI¿ØÖÆÆ÷ºÍÄÚÖõÄ·ÓÉÆ÷£¬Äú¿ÉÒÔ¿ìËÙ½¨Éè±ê×¼µÄREST API¡£Ê¹ÓÃLaravelµÄ²âÊÔ¹¤¾ß±àд²âÊÔÓÃÀý£¬¼ì²éAPI¹¦Ð§ÊÇ·ñÕý³£ÊÂÇé¡£ÓÅÒìµÄÎĵµºÍÉçÇøÖ§³Ö£¬ÊÇÈÃLaravel³ÉΪ¿ª·¢Ö°Ô±×îÊܽӴýµÄ¿ò¼ÜÖ®Ò»µÄÒªº¦ÒòËØ¡£

ÒÔÉϾÍÊÇlaravelÔõÑùдapiµÄÏêϸÄÚÈÝ£¬¸ü¶àÇë¹Ø×¢±¾ÍøÄÚÆäËüÏà¹ØÎÄÕ£¡

ÃâÔð˵Ã÷£ºÒÔÉÏչʾÄÚÈÝȪԴÓÚÏàÖúýÌå¡¢ÆóÒµ»ú¹¹¡¢ÍøÓÑÌṩ»òÍøÂçÍøÂçÕûÀí£¬°æȨÕùÒéÓë±¾Õ¾Î޹أ¬ÎÄÕÂÉæ¼°¿´·¨Óë¿´·¨²»´ú±í×ðÁú¿­Ê±¹ÙÍøµÇ¼ÂËÓÍ»úÍø¹Ù·½Ì¬¶È£¬Çë¶ÁÕß½ö×ö²Î¿¼¡£±¾ÎĽӴýתÔØ£¬×ªÔØÇë˵Ã÷À´ÓÉ¡£ÈôÄúÒÔΪ±¾ÎÄÇÖÕ¼ÁËÄúµÄ°æȨÐÅÏ¢£¬»òÄú·¢Ã÷¸ÃÄÚÈÝÓÐÈκÎÉæ¼°ÓÐÎ¥¹«µÂ¡¢Ã°·¸Ö´·¨µÈÎ¥·¨ÐÅÏ¢£¬ÇëÄúÁ¬Ã¦ÁªÏµ×ðÁú¿­Ê±¹ÙÍøµÇ¼ʵʱÐÞÕý»òɾ³ý¡£

Ïà¹ØÐÂÎÅ

ÁªÏµ×ðÁú¿­Ê±¹ÙÍøµÇ¼

18523999891

¿É΢ÐÅÔÚÏß×Éѯ

ÊÂÇéʱ¼ä£ºÖÜÒ»ÖÁÖÜÎ壬9:30-18:30£¬½ÚãåÈÕÐÝÏ¢

QR code
ÍøÕ¾µØͼ