【问题标题】:Show data for only specific id in laravel-8在 laravel-8 中仅显示特定 id 的数据
【发布时间】:2021-06-11 11:10:05
【问题描述】:

现在这是错误:

这是我的帖子 假设我有两个 id 1 和 2 如果点击 id 1 它将带我到 index.blade.php 我可以上传新数据的地方。像 data_1 和 data_2 这些数据将显示在 index.blade.php 上

如果我点击 id 2,它将带我到 index.blade.php,我不想在上传 data1 和 data2 时看到 id 1 的数据。

如果我为 id 2 上传新数据,我可以在 index.blde.php 中看到这些数据

这是 ProjectController.php

<?php

namespace App\Http\Controllers;

use App\Exports\UsersExport;
use App\Models\Project;
use App\Imports\ProjectsImport;
use App\Models\Product;
use Maatwebsite\Excel\Facades\Excel;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class ProjectController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    // public function index()
    // {
    //     $product = Project::whereIn('product_id',Product::where('user_id',Auth::id())->pluck('id')->toArray())->latest()->paginate(20);
    //     $projects = Project::where('product_id',$product)->latest()->paginate(20);

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

    // public function productProjects($product_id)
    // {
    //     $product = Product::where('user_id', Auth::id())->where('id', $product_id)->firstOrFail();
    //     $projects = Project::where('product_id', $product->id)->latest()->paginate(20);

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

    public function index($product_id)
    {
        $product = Product::where('user_id', Auth::id())->where('id', $product_id)->firstOrFail();
        $projects = Project::where('product_id', $product->id)->latest()->paginate(20);

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

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

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $request->validate([
            'chapter_name' => 'required',
            'sub_section_name' => 'required',
            'title_1' => 'required',
            'description_1' => 'required',
            'image_1' => 'required',
            'image_2' => 'required',
            'image_3' => 'required',
            'title_2' => 'required',
            'description_2' => 'required',
            'title_3' => 'required',
            'description_3' => 'required',
            'video_1' => 'required',
            'video_2' => 'required',
            'video_3' => 'required',
        ]);

        // $input = $request->all();
        // $input['user_id'] = auth()->user()->id;
        // $input['product_id'] = $id;
        $input = Project::whereIn('product_id',Product::where('user_id',Auth::id())->pluck('id'));


        Project::create($input);

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

    }

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

    public function show(Product $product)
{
    return view('projects.show', [
        'projects' => $product->projects()->latest()->paginate(20),
    ]);
}

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Models\Project  $project
     * @return \Illuminate\Http\Response
     */
    public function edit(Project $project)
    {
        return view('projects.edit', compact('project'));
    }
    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Models\Project  $project
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, Project $project)
    {
        // $user_id =  Auth::user()->id ;

        $request->validate([
            'chapter_name' => 'required',
            'sub_section_name' => 'required',
            'title_1' => 'required',
            'description_1' => 'required',
            'image_1' => 'required',
            'image_2' => 'required',
            'image_3' => 'required',
            'title_2' => 'required',
            'description_2' => 'required',
            'title_3' => 'required',
            'description_3' => 'required',
            'video_1' => 'required',
            'video_2' => 'required',
            'video_3' => 'required',
        ]);

        $input = $request->all();

        $project->update($input);

        return redirect()->route('project.index')
                        ->with('success','Product updated successfully');
    }
    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Models\Project  $project
     * @return \Illuminate\Http\Response
     */
    public function destroy(Project $project)
    {
        $project->delete();

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

    public function importProject()
    {
        Excel::import(new ProjectsImport, request()->file('file'));

        return back()->with('success','Project created successfully.');
    }

    public function export()
    {
        return Excel::download(new UsersExport, 'projects.xlsx');
    }
}

这是 index.blade.php

@extends('layouts.app')

@section('content')

    <div class="row">
        <div class="col-lg-12 margin-tb">
            <div class="pull-left">
                <h2>Laravel 8 CRUD </h2>
            </div>
            <div class="d-flex flex-row-reverse flex-column">
                <div class="d-flex">
                    <a class="btn btn-success text-light mr-5" data-toggle="medel" id="mediumButton" data-target="#mediumModel"
                    data-attr="{{ route ('projects.create')}}" title="upload project">
                        <i class="fas fa-cloud-upload-alt fa-2x"></i>
                    </a>

                    <a href="{{ route('projects.index', ['product_id' => $product_id]) }}">See Projects</a>


                    <form action="{{ route('importProject') }}" method="POST" enctype="multipart/form-data" class="d-flex">
                        @csrf
                        <input type='file' name="file">

                        <button class="btn btn-info" style="margin-left: -60px" title="Import Project">
                            <i class="fas fa-cloud-upload-alt fa-2x"></i></button>

                            <a class="btn btn-warning" href="{{ route('export') }}">Export User Data</a>
                    </form>

                </div>
            </div>
            <div class="pull-right">
                <a class="btn btn-success text-light" data-toggle="modal" id="mediumButton" data-target="#mediumModal"
                    data-attr="{{ route('projects.create') }}" title="Create a project"> <i class="fas fa-plus-circle"></i>
                </a>
            </div>
        </div>
    </div>

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

    <table class="table table-bordered table-responsive-lg table-hover">
        <thead class="thead-dark">
            <tr>
                <th scope="col">No</th>
                <th scope="col">Chapter Name</th>
                <th scope="col" >Sub-Section Name</th>
                <th scope="col">Title 1</th>
                <th scope="col">Description 1</th>
                <th scope="col">Image 1</th>
                <th scope="col">Image 2</th>
                <th scope="col">Image 3</th>
                <th scope="col">Title 2</th>
                <th scope="col">Description 2</th>
                <th scope="col">Title 3</th>
                <th scope="col">Description 3</th>
                <th scope="col">Video 1</th>
                <th scope="col">Video 2</th>
                <th scope="col">Video 3</th>

                <th scope="col">Date Created</th>
                <th scope="col">Action</th>
            </tr>
        </thead>
        <tbody>
            @foreach ($projects as $project)
                <tr>
                    <td scope="row">{{ ++$i }}</td>
                    <td>{{ $project->chapter_name }}</td>
                    <td>{{ $project->sub_section_name }}</td>
                    <td>{{ $project->title_1 }}</td>
                    <td>{{ $project->description_1 }}</td>
                    <td>{{ $project->image_1 }}</td>
                    <td>{{ $project->image_2 }}</td>
                    <td>{{ $project->image_3 }}</td>
                    <td>{{ $project->title_2 }}</td>
                    <td>{{ $project->description_2 }}</td>
                    <td>{{ $project->title_3 }}</td>
                    <td>{{ $project->description_3 }}</td>
                    <td>{{ $project->video_1 }}</td>
                    <td>{{ $project->video_2 }}</td>
                    <td>{{ $project->video_3 }}</td>

                    <td>{{ date_format($project->created_at, 'jS M Y') }}</td>
                    <td>
                        <form action="{{ route('projects.destroy', $project->id) }}" method="POST">

                            <a data-toggle="modal" id="smallButton" data-target="#smallModal"
                                data-attr="{{ route('projects.show', $project->id) }}" title="show">
                                <i class="fas fa-eye text-success  fa-lg"></i>
                            </a>

                            <a class="text-secondary" data-toggle="modal" id="mediumButton" data-target="#mediumModal"
                                data-attr="{{ route('projects.edit', $project->id) }}">
                                <i class="fas fa-edit text-gray-300"></i>
                            </a>
                            @csrf
                            @method('DELETE')

                            <button type="submit" title="delete" style="border: none; background-color:transparent;">
                                <i class="fas fa-trash fa-lg text-danger"></i>
                            </button>
                        </form>
                    </td>
                </tr>
            @endforeach
        </tbody>
    </table>

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


    <!-- small modal -->
    <div class="modal fade" id="smallModal" tabindex="-1" role="dialog" aria-labelledby="smallModalLabel"
        aria-hidden="true">
        <div class="modal-dialog modal-sm" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body" id="smallBody">
                    <div>
                        <!-- the result to be displayed apply here -->
                    </div>
                </div>
            </div>
        </div>
    </div>


    <!-- medium modal -->
    <div class="modal fade" id="mediumModal" tabindex="-1" role="dialog" aria-labelledby="mediumModalLabel"
        aria-hidden="true">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body" id="mediumBody">
                    <div>
                        <!-- the result to be displayed apply here -->
                    </div>
                </div>
            </div>
        </div>
    </div>


    <script>
        // display a modal (small modal)
        $(document).on('click', '#smallButton', function(event) {
            event.preventDefault();
            let href = $(this).attr('data-attr');
            $.ajax({
                url: href,
                beforeSend: function() {
                    $('#loader').show();
                },
                // return the result
                success: function(result) {
                    $('#smallModal').modal("show");
                    $('#smallBody').html(result).show();
                },
                complete: function() {
                    $('#loader').hide();
                },
                error: function(jqXHR, testStatus, error) {
                    console.log(error);
                    alert("Page " + href + " cannot open. Error:" + error);
                    $('#loader').hide();
                },
                timeout: 8000
            })
        });

        // display a modal (medium modal)
        $(document).on('click', '#mediumButton', function(event) {
            event.preventDefault();
            let href = $(this).attr('data-attr');
            $.ajax({
                url: href,
                beforeSend: function() {
                    $('#loader').show();
                },
                // return the result
                success: function(result) {
                    $('#mediumModal').modal("show");
                    $('#mediumBody').html(result).show();
                },
                complete: function() {
                    $('#loader').hide();
                },
                error: function(jqXHR, testStatus, error) {
                    console.log(error);
                    alert("Page " + href + " cannot open. Error:" + error);
                    $('#loader').hide();
                },
                timeout: 8000
            })
        });

    </script>

@endsection

这是我的 web.php

<?php

use App\Http\Controllers\ProductController;
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\ProjectController;
use App\Http\Controllers\MyController;



/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

Route::get('/', function () {
    return view('welcome');
});

Route::middleware(['auth:sanctum', 'verified'])->get('/dashboard', function () {
    return view('dashboard');
})->name('dashboard');

Route::resource('products', ProductController::class);

Route::post('projects/importProject', [ProjectController::class, 'importProject'])->name('importProject');

// Route::resource('projects', ProjectController::class);
Route::resource('projects', 'ProjectController', ['parameters' => [
    'index' => 'product_id'
]]);

Route::get('export', [MyController::class, 'export'])->name('export');

这是 RouteServiceProvidor.php

<?php

namespace App\Providers;

use Illuminate\Cache\RateLimiting\Limit;
use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Support\Facades\Route;

class RouteServiceProvider extends ServiceProvider
{
    /**
     * The path to the "home" route for your application.
     *
     * This is used by Laravel authentication to redirect users after login.
     *
     * @var string
     */
    public const HOME = '/products';

    /**
     * The controller namespace for the application.
     *
     * When present, controller route declarations will automatically be prefixed with this namespace.
     *
     * @var string|null
     */
    // protected $namespace = 'App\\Http\\Controllers';

    /**
     * Define your route model bindings, pattern filters, etc.
     *
     * @return void
     */
    // public function boot()
    // {
    //     $this->configureRateLimiting();

    //     $this->routes(function () {
    //         Route::prefix('api')
    //             ->middleware('api')
    //             ->namespace($this->namespace)
    //             ->group(base_path('routes/api.php'));

    //         Route::middleware('web')
    //             ->namespace($this->namespace)
    //             ->group(base_path('routes/web.php'));
    //     });
    // }

    public function boot()
    {
        $this->configureRateLimiting();

        $this->routes(function () {
            Route::prefix('api')
                ->middleware('api')
                ->namespace($this->namespace)
                ->group(base_path('routes/api.php'));

            Route::middleware('web')
                ->namespace('App\Http\Controllers') // <<<- Here is the change
                ->group(base_path('routes/web.php'));
        });
    }

    /**
     * Configure the rate limiters for the application.
     *
     * @return void
     */
    protected function configureRateLimiting()
    {
        RateLimiter::for('api', function (Request $request) {
            return Limit::perMinute(60)->by(optional($request->user())->id ?: $request->ip());
        });
    }
}

【问题讨论】:

  • 我没有得到“但正在显示 user_id 的所有数据”。请详细说明并举例说明您想要的结果
  • 假设我在用户表中有 id 为 1 的用户,让我们调用 id user1。 user1 可以创建许多产品,假设 user1 创建 product1、product2 和 product3。现在 user1 可以在所有产品中创建许多项目。假设 user1 在 product1 中创建 project1 和 project2 并将其显示在视图中。 user1 在 products2 中创建一些新项目,但在 product2 中创建任何项目之前,此处显示的 project1 和 project2 不应在此处显示。在 product2 视图中应该是空的。当 user1 在 product2 中创建项目时,product2 下的项目将显示在视图中
  • 你可以看到我已经编辑了我的帖子

标签: laravel-8 laravel-excel


【解决方案1】:

这是因为您一次获得了特定用户的所有项目。您需要指定您想要的产品项目。您必须使用产品 ID 执行此操作。

在 ProjectController.php 中:

public function index($product_id)
    {
        $product = Product::where('user_id', Auth::id())->where('id', $product_id)->firstOrFail();
        $projects = Project::where('product_id', $product->id))->latest()->paginate(20);

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

在你的web.php:

Route::resource('projects', 'ProjectController', ['parameters' => [
    'index' => 'product_id'
]]);

请注意,您应该像这样在RouteServiceProvider.php 中定义控制器命名空间:

public function boot()
    {
        $this->configureRateLimiting();

        $this->routes(function () {
            Route::prefix('api')
                ->middleware('api')
                ->namespace($this->namespace)
                ->group(base_path('routes/api.php'));

            Route::middleware('web')
                ->namespace('App\Http\Controllers') // <<<- Here is the change
                ->group(base_path('routes/web.php'));
        });
    }

然后你可以在你的视图中使用这个带有名字的路由,像这样:

 <a href="{{ route('projects.index', ['product_id' => $product_id]) }}">See Projects</a>

【讨论】:

  • 我无法将 product_id 声明为变量,他们向我显示此错误太少的参数函数 App\Http\Controllers\ProjectController::index(), 0 在 C:\xampp\htdocs\ContentBaseApp 中传递\vendor\laravel\framework\src\Illuminate\Routing\Controller.php 位于第 54 行,预计为 1。
  • 因为我认为您为index 方法设置了一个参数,而您没有将该参数传递给该方法。我更新了答案并为此productProjects 方法添加了路线。
  • 我应该对 index() 方法进行哪些更改? ``` public function index() { $projects = Project::whereIn('product_id',Product::where('user_id',Auth::id())->pluck('id')->toArray() )->最新()->分页(20); return view('projects.index', compact('projects')) ->with('i', (request()->input('page', 1) - 1) * 5); }````
  • 请你再看看我的 ProjectController 和 web.php 我已经编辑了我的帖子
  • @AbdullahAlShahed 在索引方法中,它返回所有用户的项目,如您所见。但是在我写的productProjects 的新方法中,您只能获得特殊产品的项目。你有什么困难?它不起作用?
猜你喜欢
  • 2022-01-24
  • 2023-04-10
  • 2020-10-25
  • 2021-07-25
  • 2023-04-04
  • 2019-05-13
  • 2023-01-08
  • 2018-04-19
  • 1970-01-01
相关资源
最近更新 更多