php 我想将我的laravel API与React Js集成

xtfmy6hx  于 2023-06-21  发布在  PHP
关注(0)|答案(1)|浏览(70)

我想把我的分页API与SQL DB中的数据集成在一起。我想显示我的应用程序的前端作为分页表来自laravel。如何解决呢?我的一些代码是Fruit Controller

<?php

namespace App\Http\Controllers\API;

use Illuminate\Http\Request;
use App\Http\Controllers\API\BaseController as BaseController;
use App\Models\Fruit;
use Validator;
use App\Http\Resources\FruitResource;

class FruitController extends BaseController
{
    /**
     * Display a listing of the resource.
     *
     */
    public function index(Request $request)
    {
        $name = $request->input('name');
        $family = $request->input('family');

        $query = Fruit::query();

        if ($name) {
            $query->where('name', 'LIKE', '%' . $name . '%');
        }

        if ($family) {
            $query->where('family', 'LIKE', '%' . $family . '%');
        }

        $fruits = $query->get();
        return $this->sendResponse(FruitResource::collection($fruits), 'Fruits retrieved successfully.');
    }

    public function fruits(Request $request)
    {
        $fruits = Fruit::with("nutritions")->paginate(5);
        return view('fruits', compact('fruits'));
    }
    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     */
    public function store(Request $request)
    {
        $input = $request->all();

        $validator = Validator::make($input, [
            'external_id' => 'required',
            'name' => 'required',
            'family' => 'required',
            'order' => 'required',
            'genus' => 'required'
        ]);

        if ($validator->fails()) {
            return $this->sendError('Validation Error.', $validator->errors());
        }

        $fruit = Fruit::create($input);

        return $this->sendResponse(new FruitResource($fruit), 'Fruit created successfully.');
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     */
    public function show($id)
    {
        $fruit = Fruit::find($id);

        if (is_null($fruit)) {
            return $this->sendError('Fruit not found.');
        }

        return $this->sendResponse(new FruitResource($fruit), 'Fruit retrieved successfully.');
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     */
    public function update(Request $request, Fruit $fruit)
    {
        $input = $request->all();

        $validator = Validator::make($input, [
            'external_id' => 'required',
            'name' => 'required',
            'family' => 'required',
            'order' => 'required',
            'genus' => 'required',
        ]);

        if ($validator->fails()) {
            return $this->sendError('Validation Error.', $validator->errors());
        }

        $fruit->external_id = $input['external_id'];
        $fruit->name = $input['name'];
        $fruit->family = $input['family'];
        $fruit->order = $input['order'];
        $fruit->genus = $input['genus'];
        $fruit->save();

        return $this->sendResponse(new FruitResource($fruit), 'Fruit updated successfully.');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     */
    public function destroy(Fruit $fruit)
    {
        $fruit->delete();

        return $this->sendResponse([], 'Product deleted successfully.');
    }
}

以下是我的路线:

    • api. php**
<?php

use App\Models\Fruit;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
// use App\Models\FruitsNutrition;

  
// use App\Http\Controllers\API\RegisterController;
use App\Http\Controllers\API\AuthController;
use App\Http\Controllers\API\FruitController;
use App\Http\Controllers\API\FruitNutritionsController;  
/*
|--------------------------------------------------------------------------
| 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::controller(AuthController::class)->group(function(){
    Route::post('login', 'login');
    Route::post('register', 'register');
});
        
// Route::middleware('auth:sanctum')->group( function () {
    Route::resource('fruits', FruitController::class);
    // Route::resource('nutritions', FruitNutritionsController::class);
// });

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

Route::get('/fruits', function(){
    $fruits = Fruit::get();
    return response()->json($fruits);
});

React:我有个习惯。如何修改自定义分页?
下面是我的代码Design.jsx

// /* eslint-disable react/prop-types */ // TODO: upgrade to latest eslint tooling
import "../src/App.css";
import axios from "axios";
import { useEffect, useState, useMemo } from "react";
import Pagination from "./Pagination";
import { Link } from "react-router-dom";

let PageSize = 2;

export default function Design() {
  const [search, setSearchTerm] = useState("all");
  const [records, setRecords] = useState([]);
  const [suggestions, setSuggestions] = useState([]);
  const [currentPage, setCurrentPage] = useState(1);

  const localData = () => {
    const data = window.localStorage.getItem("pnum");
    // console.log(data)
    if (data === null) {
      return 1;
    } else {
      return JSON.parse(data);
    }
  };

  useEffect(() => {
    setCurrentPage(localData());
    searchRecords();
  }, []);

  const currentTableData = useMemo(() => {
    const firstPageIndex = (currentPage - 1) * PageSize;
    const lastPageIndex = firstPageIndex + PageSize;
    return records.slice(firstPageIndex, lastPageIndex);
  }, [currentPage, records]);

  const searchRecords = async () => {
    try {
      const res = await axios.get(`http://localhost:8000/api/fruits`);
      setRecords(search === "all" ? res.data.data : [res.data.data]);
    } catch (error) {
      console.error("Error searching record:", error);
      setRecords([]);
    }
  };

  const fetchSuggestions = async (input) => {
    try {
      const res = await axios.get(`https://fruityvice.com/api/fruit/all`);
      const fruits = res.data.map((fruit) => fruit.name);
      const filteredSuggestions = fruits.filter((fruit) =>
        fruit.toLowerCase().includes(input.toLowerCase())
      );
      setSuggestions(filteredSuggestions);
    } catch (error) {
      console.error("Error fetching suggestions:", error);
      setSuggestions([]);
    }
  };

  const handleInputChange = (e) => {
    const inputValue = e.target.value;
    setSearchTerm(inputValue);
    fetchSuggestions(inputValue);
  };

  const getTotalNutritions = (item) => {
    return Object.values(item.nutritions).reduce(
      (total, value) => total + Math.trunc(value),
      0
    );
  };

  return (
    <>
      <h1 className="main--heading">Fruit Project</h1>
      <div className="main">
        <input
          className="input"
          onChange={handleInputChange}
          list="suggestions"
          placeholder="Search Fruit"
        />
        <datalist id="suggestions">
          {suggestions.map((fruit, index) => (
            <option key={index} value={fruit} />
          ))}
        </datalist>
        <button className="btn" onClick={searchRecords}>
          Search Fruit
        </button>
      </div>
      <div>
        <table>
          <thead>
            <tr>
              <th>Sr No</th>
              <th>Name</th>
              <th>Family</th>
              <th>Order</th>
              <th>Nutritions</th>
              <th>Genus</th>
            </tr>
          </thead>
          <tbody>
            {Array.isArray(currentTableData) && currentTableData.length > 0 ? (
              currentTableData
                // .sort((a, b) => a.id - b.id)
                .map((item) => (
                  <tr key={item.id}>
                    <td>{item.id}</td>
                    <td>
                      {item.name}&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                      <Link to={`/details/${item.id}`}>View Details</Link>
                    </td>
                    <td>{item.family}</td>
                    <td>{item.order}</td>
                    {/* <td>{getTotalNutritions(item)}</td> */}
                    <td>{item.genus}</td>
                  </tr>
                ))
            ) : (
              <tr>
                <td>No data available</td>
              </tr>
            )}
          </tbody>
        </table>
        <Pagination
          className="pagination-bar"
          currentPage={currentPage}
          totalCount={records.length}
          pageSize={PageSize}
          onPageChange={(page) => {
            setCurrentPage(page);
            window.localStorage.setItem("pnum", page);
          }}
        />
      </div>
    </>
  );
}

请帮我去掉它。谢谢

pxy2qtax

pxy2qtax1#

关于Laravel部分,我可以强调几件事,你确实有一个资源路由,而不是使用

Route::apiResource('fruits', FruitController::class);

因此,这将生成相同的路由,而不使用/create和/edit
你也有

Route::get('/fruits', function(){
  $fruits = Fruit::get();
  return response()->json($fruits);
});

这个函数返回所有的fruits,不带分页,你实际上不需要它,你也不需要这个函数,因为你没有在任何地方调用它

public function fruits(Request $request)
{
    $fruits = Fruit::with("nutritions")->paginate(5);
    return view('fruits', compact('fruits'));
}

我只是建议你删除函数fruits和route /fruits,只使用route资源,并将函数索引替换为你拥有的函数fruits。
这样看起来就像

public function index(Request $request)
{
    $name = $request->input('name');
    $family = $request->input('family');

    $query = Fruit::query();

    if ($name) {
        $query->where('name', 'LIKE', '%' . $name . '%');
    }

    if ($family) {
        $query->where('family', 'LIKE', '%' . $family . '%');
    }

    $fruits = $query->paginate(5);
    return $this->sendResponse(FruitResource::collection($fruits),  'Fruits retrieved successfully.');
}

希望这能有所帮助

相关问题