Laravel笔记-搭建Restful风格的后端

2023-05-16

首先创建Controller和resource

php artisan make:controller ProductsController -r
php artisan make:resource ProductResource

将ProductsController.php改为:

<?php

namespace App\Http\Controllers;

use App\Http\Resources\ProductResource;
use App\Models\Products;
use Illuminate\Http\Request;

class ProductsController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        return Products::all();
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $productName = $request->input('name');
        $productPrice = $request->input('price');
        $productDescription = $request->input('description');

        $product = Products::create([
            'name' => $productName,
            'price' => $productPrice,
            'description' => $productDescription,
        ]);
        return response()->json([
            'data' => new ProductResource($product)
        ], 201);
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show(Products $product)
    {
        return new ProductResource($product);
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, Products $product)
    {
        $productName = $request->input('name');
        $productPrice = $request->input('price');
        $productDescription = $request->input('description');

        $product->update([
            'name' => $productName,
            'price' => $productPrice,
            'description' => $productDescription
        ]);

        return response()->json([
            'data' => new ProductResource($product)
        ], 200);
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy(Products &$product)
    {
        $product->delete();
        return response()->json(null, 204);
    }
}

PrductResource.php

<?php

namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\JsonResource;

class ProductResource extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array|\Illuminate\Contracts\Support\Arrayable|\JsonSerializable
     */
    public function toArray($request)
    {
        return [
          'id' => $this->id,
          'productName' => $this->name,
          'discountedPrice' => "$" . ($this->price * 0.8),
          'discount' => "$" . ($this->price * 0.2),
          'productDescription' => $this->description,
        ];
    }
}

这里需要在routes/api.php中添加代码,不用在web.php中添加

<?php

use App\Http\Controllers\ProductsController;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;

/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/

Route::middleware('auth:sanctum')->get('/user', function (Request $request) {
    return $request->user();
});


Route::get('products', [ProductsController::class, 'index'])->name('products.index');
Route::get('products/{product}', [ProductsController::class, 'show'])->name('products.show');
Route::post('products', [ProductsController::class, 'store'])->name('products.store');
Route::put('products/{product}', [ProductsController::class, 'update'])->name('products.update');
Route::delete('products/{product}', [ProductsController::class, 'destroy'])->name('products.destroy');

运行截图如下:

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Laravel笔记-搭建Restful风格的后端 的相关文章

  • Elasticquent(ElasticSearch) Laravel 限制

    您好 我尝试使用 elasticSearch 查询获取所有结果 但如果 limit 值为 null 则仅返回 10 个结果 videos Video searchByQuery match gt field gt request gt fi
  • Laravel - 删除整个集合

    我有文章的图像 当我更新文章时 我想检查图像是否相同 如果不是 我想删除它们 但如果可能的话 我想删除整个集合而不进行其他查询 诸如此类就像我在下面的代码中一样 images gt delete 这是我的功能 images Media wh
  • 使用factory faker创建的图像在存储在storage/public/images文件夹中时会被删除

    我正在尝试用假图像填充我的数据库 但是当 faker 将其保存到我的图像文件夹中时 一秒钟后它被删除 并且在我的数据库字段中我得到 0 我可以访问http lorempixel com http lorempixel com 也可以 pin
  • Eloquent/Laravel 三路多对多关系

    我对 Laravel 和 Eloquent 是全新的 而且我对 ORM 的经验也很少 假设我有三个数据库表 Widgets Actions Users 我建模了一个连接表 其中包含以下列 widget id action id user i
  • 如何比较两个碳时间戳?

    我有两个时间戳 edited at 我创建的 和created at Laravel 的 在数据库中 两者都有时间戳类型和默认值 0000 00 00 00 00 00 但是 var dump edited at variable 正在给出
  • 没有适用于机器人的 Laravel 会话

    我在大型 Laravel 项目和 Redis 存储方面遇到问题 我们将会话存储在 Redis 中 我们已经有 28GB 的 RAM 然而 它的运行速度仍然相对较快 达到了极限 因为我们有来自搜索引擎机器人的大量点击 每天超过 250 000
  • Laravel 注册成功后如何重定向到上一页?

    现在redirectTo被设定为 home 我想知道如何重定向到上一页 我尝试使用 protected redirectTo URL previous 但我得到解析错误 期待 or 解决这个问题的最佳解决方案是什么 我想我需要重写 redi
  • Laravel 内存问题?

    各位 我在 DO 服务器上遇到这样的问题 我已经尝试了一切 整个网站在使用 Homestead 的 Linux 服务器上 100 正常工作 但上传后 它只能工作一次 在重新加载或刷新页面后会多次下降 我尝试增加 apache 服务器的内存
  • PHP Laravel 路由问题

    我的设置目前看起来像这样 应用程序 控制器 register php class register Controller extends Base Controller public restful true public function
  • Chart.js - 如何将数组集合推入数据集

    我一直在尝试多种方法将数组集合推送到数据集中 任何人都可以帮助我根据下面的代码将数组推入堆积图表中 这是例子 Codepen 堆叠栏 https codepen io narendrajadhav pen abzpWam JavaScrip
  • Laravel eloquent 获取关系数

    我使用 Laravel 5 3 我有 2 张桌子 Articles id cat id title And Category id parent id title 我在模型中定义了我的关系 Article model public func
  • 开发中的 Laravel 和视图缓存——无法立即看到变化

    我和一些朋友决定开始一个项目 我们偶然发现了 Laravel 并认为它可能是一个很好的工具 我们开始在本地使用它来开发一些页面 并注意到一些奇怪的事情 当我们用不同的信息更新视图时 大约需要 5 到 10 分钟视图信息才会发生变化 这就像
  • Laravel 克隆查询字符串

    是否可以克隆一个查询字符串 以便我可以编写一次并在不影响其他结果的情况下进行长时间的更改 query DB table users gt where id 123 queryGet query queryPaginate query que
  • 预期响应代码 250,但收到代码“530”,并显示消息“530 5.7.1 需要身份验证”

    我尝试配置 SMTP 邮件时遇到此错误laravel 这是我的配置 env MAIL DRIVER smtp MAIL HOST smtp mailtrap io MAIL PORT 2525 MAIL USERNAME fff3c01db
  • 使用 v2 PHP SDK 与 Laravel 的 PayPal 集成失败

    我正在尝试将通过 PayPal 的简单付款与沙箱企业帐户集成 我发现用于 v1 付款的 PayPal PHP SDK 已被弃用 所以我只想使用 Laravel 测试较新的 v2 SDK 在尝试测试 PayPal 演示时 我遇到了多个错误 例
  • 在 Laravel 中使用 grpc,“未找到‘Grpc\ChannelCredentials’类”。

    我正在尝试在 Laravel 项目中使用 grpc 这是我的composer json 文件的一部分 require datto protobuf php dev master google auth 0 7 0 grpc grpc dev
  • Laravel Eloquent 多对多查询 whereIn

    在我的应用程序中 我更新了关系one to many to many to many我正在尝试找出一种方法来保留相关功能 假设我有两个相关的表 例如狗和主人 如果我有很多主人 并且我想获取这些主人的狗 ID 列表 我应该如何雄辩地做到这一点
  • 在浏览器中就绪的 DOM 上缺少语言翻译弹出窗口:Laravel 5.2

    我的控制器中有以下代码 public function AllCountries Countries new App DataAccess CountryData gt GetAllCountries app gt setLocale fr
  • 未找到“Mockery”类

    我使用 laravel 4 1 框架 并且阅读了 Laravel testing decoded 这是 Jeffrey Wey 写的一本电子书 我想测试我的模态用户和我的方法setPasswordAttribute password 我的单
  • Bootstrap 4 正在破坏 Stripe Elements

    我正在尝试将 Stripe 与我的 Laravel 网站集成 为了做到这一点 我正在遵循他们网站上的文档 https stripe com docs stripe js elements quickstart https stripe co

随机推荐