【问题标题】:Nested resource controllers and routes with ajax使用 ajax 嵌套资源控制器和路由
【发布时间】:2021-10-19 23:46:48
【问题描述】:

我为web.php使用了以下代码。

Route::resource('products', 'ProductController');
Route::resource('products.galleries', 'GalleryController');

在这个地址 http://localhost:8000/admin/products ,我加了这段代码

<td><a href="{{ route('products.galleries.create', $product->id) }}">Create</a></td>

然后我在create方法中定义它,并控制GalleryController

GalleryController.php

public function create(Product $product)
{
    return view('Admin.galleries.create', compact('product'));
}

画廊是空的

我正在使用 下拉菜单

$.ajax({
    headers: {
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content'),
    },
    type: 'POST',
    url: '{{ route('products.galleries.destroy', [$product->id, $gallery->id]) }}',
    date: {filename, name},
    success: function (data) {
        console.log('File has been successfully removed!!');
    },
    error: function (e){
        console.log(e);
    },
});

我收到此错误

未定义变量:图库

谁能告诉我如何解决这个问题?

【问题讨论】:

    标签: php laravel dropdown


    【解决方案1】:

    在您的GalleryController 中,库实例 ($gallery) 永远不会发送到视图:

    public function create(Product $product)
    {
        return view('Admin.galleries.create', compact('product')); // where is $gallery ?
    }
    

    这就是为什么在您看来,当您尝试使用 $gallery(在您的 javascript 中,destroy 路由中)时,您会收到错误。

    您有多种方法可以解决此问题,具体取决于您想要实现的目标。但是,如果没有更多信息,最快的解决方案是将 JavaScript 代码包装在条件中。

    @isset($gallery)
        $.ajax({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content'),
            },
            type: 'POST',
            url: '{{ route('products.galleries.destroy', [$product->id, $gallery->id]) }}',
            date: {filename, name},
            success: function (data) {
                console.log('File has been successfully removed!!');
            },
            error: function (e){
                console.log(e);
            },
        });
    @endisset
    

    我认为您这样做是因为您想在$gallery 变量可用时重用视图的这一部分,例如products.galleries.indexproducts.galleries.show

    通过将 javascript 包装在 @isset($gallery) 标记中,您将确保它仅在 $gallery 实例可用时执行。

    【讨论】:

      【解决方案2】:

      问题很简单,因为 ajax 的 url 部分中没有 $gallery 变量的定义。

      您能否解释一下destroy 路由中$gallery 变量的用途以及如何将它传递给create 刀片。

      【讨论】:

        猜你喜欢
        • 2013-01-23
        • 2013-02-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-08-15
        • 2013-01-31
        • 1970-01-01
        相关资源
        最近更新 更多