尊龙凯时人生就是博

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
sitemap¡¢ÍøÕ¾µØͼ