首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在laravel-8中仅显示特定id的数据

在laravel-8中仅显示特定id的数据
EN

Stack Overflow用户
提问于 2021-06-11 19:10:05
回答 1查看 64关注 0票数 0

这是现在的错误:

这是我的帖子

假设我有两个id1和2,如果单击id1,它会将我带到index.blade.php,在那里我可以上传新数据。像data_1和data_2一样,这些数据将显示在index.blade.php上

如果我点击id2,它会把我带到index.blade.php,在那里我不想看到id1的数据,因为我上传了data1和data2。

如果我上传id2的新数据,我可以在index.blde.php中看到这些数据。

这是ProjectController.php

代码语言:javascript
复制
<?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

代码语言:javascript
复制
@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

代码语言:javascript
复制
<?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

代码语言:javascript
复制
<?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());
        });
    }
}
EN

回答 1

Stack Overflow用户

发布于 2021-06-12 13:14:35

这是因为您可以一次性获取特定用户的所有项目。您需要指定所需的产品项目。您必须对产品id执行此操作。

在ProjectController.php中:

代码语言:javascript
复制
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

代码语言:javascript
复制
Route::resource('projects', 'ProjectController', ['parameters' => [
    'index' => 'product_id'
]]);

注意,您应该在RouteServiceProvider.php中定义控制器命名空间,如下所示:

代码语言:javascript
复制
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'));
        });
    }

然后,您可以在视图中使用此路由的名称,如下所示:

代码语言:javascript
复制
 <a href="{{ route('projects.index', ['product_id' => $product_id]) }}">See Projects</a>
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/67935972

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档