首页 > 解决方案 > 试图在 laravel-8 的 index.blade.php 的 listView 中显示为特定用户注册的某些产品

问题描述

我可以使用外键作为“user_id”为特定用户注册产品,用户有许多产品一对多的关系。您可以在 user_id 中看到,用户 2 有 2 个产品持有 id 5 和 7 我想显示当我使用用户 2 登录时,它只会显示产品 5 和 7,而不是用户 1 注册的产品 6。但我的代码

 public function index()
    {
        $products = Product::latest()->paginate(20);
         return view('products.index',compact('products'))
         ->with('i', (request()->input('page', 1) - 1) * 5);
    }

在 index.blede.php 中也显示产品 6 看到图像索引图像 你可以看到索引有另一个问题它显示 id 5 作为 id 1 和 id 6 作为 id 2 和 id 7 作为 id 3 如何修复它你能帮我吗?这是我完整的 ProductController.php

<?php

namespace App\Http\Controllers;

use App\Models\Product;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Http\Requests\Admin\StoreTagsRequest;
use App\Models\User;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;

class ProductController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */

     public function indexGetProducts(){
         return User::find(1)->getProducts;
     }

    public function index()
    {
        $products = Product::latest()->paginate(20);
         return view('products.index',compact('products'))
         ->with('i', (request()->input('page', 1) - 1) * 5);
        // $products= Product::where('user_id',auth()->user()->id)->orderby('created_at','desc')->get();

        // return view('products.index',compact('products'))->with('i', (request()->input('page', 5) - 1) * 5);

    }

    function authapi(Request $request)
    {
        $user = User:: where('email', $request->email)->first();
        if(!$user || !Hash::check($request->password, $user->password)){
            return response([
                'message' => ['These credentials do not match our records.']
            ],404);
        }

        $token = $user -> createToken('my-app-token')->plainTextToken;

        $response = [
            'user' => $user,
            'token' => $token
        ];

        return response($response,201);
    }

    function all_app_jsons(){
        return Product::all();
    }

    function search_by_name($name){
        return Product::where('name','like','%'.$name.'%')->get();
    }

    function search_by_id($id){
        return Product::where('id',$id)->get();
    }
    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view('products.create');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        //$tag = Product::create($request->all());

        //return redirect()->route('admin.tags.index');
        $request->validate([
            'name' => 'required',
            'detail' => 'required',
            'color' => 'required',
            'image' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
            'logo' => 'required|mimes:jpeg,png,jpg,gif,svg|max:1024',
        ]);

          $input = $request->all();
         // $request->validated();
        $input['user_id'] = auth()->user()->id;

        if ($image = $request->file('image')) {
            $destinationPath = 'image/';
            $profileImage = date('YmdHis') . "." . $image->getClientOriginalExtension();
            $image->move($destinationPath, $profileImage);
            $input['image'] = "$profileImage";
        }

        if ($logo = $request->file('logo')) {
            $destinationPath = 'logo/';
            $profileLogo = date('YmdHis') . "." . $logo->getClientOriginalExtension();
            $logo->move($destinationPath, $profileLogo);
            $input['logo'] = "$profileLogo";
        }

        Product::create($input);

        return redirect()->route('products.index')
                        ->with('success','Product created successfully.');
    }

    /**
     * Display the specified resource.
     *
     * @param  \App\Product  $product
     * @return \Illuminate\Http\Response
     */
    public function show(Product $product)
    {
        return view('products.show',compact('product'));
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Product  $product
     * @return \Illuminate\Http\Response
     */
    public function edit(Product $product)
    {
        return view('products.edit',compact('product'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Product  $product
     * @return \Illuminate\Http\Response
     */
    // public function update(Request $request, Product $product)
    public function update(Request $request, $product_id)
    {
        $user_id =  Auth::user()->id ;

        $request->validate([
            'name' => 'required',
            'detail' => 'required',
            'color' => 'required'
        ]);

        $input = $request->all();

        if ($image = $request->file('image')) {
            $destinationPath = 'image/';
            $profileImage = date('YmdHis') . "." . $image->getClientOriginalExtension();
            $image->move($destinationPath, $profileImage);
            $input['image'] = "$profileImage";
        }else{
            unset($input['image']);
        }

        if ($logo = $request->file('logo')) {
            $destinationPath = 'logo/';
            $profileLogo = date('YmdHis') . "." . $logo->getClientOriginalExtension();
            $logo->move($destinationPath, $profileLogo);
            $input['logo'] = "$profileLogo";
        }else{
            unset($input['logo']);
        }

        $product_id->update($input);

        return redirect()->route('products.index')
                        ->with('success','Product updated successfully');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Product  $product
     * @return \Illuminate\Http\Response
     */
    public function destroy(Product $product)
    {
        $product->delete();

        return redirect()->route('products.index')
                        ->with('success','Product deleted successfully');
    }

    // function indextwo(){
    //     //return DB::select("select * from  products");
    //    //DB::table('products')->orderBy('id','desc')->first();
    //    return Product::orderBy('id', 'DESC')->first();
    // }

}

这是我的 index.blade.php

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>index</title>

    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-eOJMYsd53ii+scO/bJGFsiCZc+5NDVN2yr8+0RDqr0Ql0h+rP48ckxlpbzKgwra6" crossorigin="anonymous">
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta3/dist/js/bootstrap.bundle.min.js" integrity="sha384-JEW9xMcG8R+pH31jmWH6WWP0WintQrMb4s7ZOdauHnUtxwoG2vI5DkLtS3qm9Ekf" crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.9.1/dist/umd/popper.min.js" integrity="sha384-SR1sx49pcuLnqZUnnPwx6FCym0wLsk5JZuNx2bPPENzswTNFaQU1RDvt3wT4gWFG" crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta3/dist/js/bootstrap.min.js" integrity="sha384-j0CNLUeiqtyaRmlzUHCPZ+Gy5fQu0dQ6eZ/xAww941Ai1SxSY+0EQqNXNE6DZiVc" crossorigin="anonymous"></script>
</head>
<body>


@extends('products.layout')

@section('content')
    <div class="row">
        <div class="pull-right">
            <!-- Authentication -->
               <form method="POST" action="{{ route('logout') }}" style="margin: 20px">
                   @csrf

                   <x-jet-dropdown-link href="{{ route('logout') }}"
                           onclick="event.preventDefault();
                                   this.closest('form').submit();">
                       {{ __('Log Out') }}
                   </x-jet-dropdown-link>
               </form>
           </div>
        {{--  --}}
        <div></div>
        <div class="col-lg-12 margin-tb">
            <div class="pull-left">
                <h2>Click Button</h2>
            </div>
            <div class="pull-right">
                <a class="btn btn-success" href="{{ route('products.create') }}"> Create New App</a>
            </div>
        </div>
    </div>

    @if ($message = Session::get('success'))
        <div class="alert alert-success">
            <p>{{ $message }}</p>
        </div>
    @endif

    <table class="table table-bordered">
        <tr>
            <th>No</th>
            <th>App Name</th>
            <th>App Logo</th>
            <th>Splash Image</th>
            <th>Description</th>
            <th>Color</th>
            <th width="280px">Action</th>
        </tr>
        @foreach ($products as $product)
        <tr>
            <td>{{ ++$i }}</td>
            <td>{{ $product->name }}</td>
            <td><img src="/logo/{{ $product->logo }}" width="100px"></td>
            <td><img src="/image/{{ $product->image }}" width="100px"></td>

            <td>{{ $product->detail }}</td>
            <td>{{ $product->color }}</td>
            <td>
                <form action="{{ route('products.destroy',$product->id)}}" method="POST">

                    <a class="btn btn-info" href="{{ route('products.show',$product->id) }}">Show</a>

                    <a class="btn btn-primary" href="{{ route('products.edit',$product->id) }}">Edit</a>

                    <a class="btn btn-info" href="api/json_link">All Json</a>

                    <a class="btn btn-info" href="api/SearchById">JsonById</a>

                    <a class="btn btn-info" href="api/SearchByName">JsonByName</a>

                    @csrf
                    @method('DELETE')

                    <button type="submit" class="btn btn-danger">Delete</button>
                </form>
            </td>
        </tr>
        @endforeach
    </table>

    {!! $products->links() !!}

@endsection
</body>
</html>

标签: laravellaravel-8

解决方案


您在没有设置条件的情况下获取产品,最新的方法是基于时间戳而不是 id。

您应该添加 where 子句,如Product::where('user_id', 2). 如果你想根据 id 获取,你可以使用latest('id').


推荐阅读