Laravel 使用变量创建路线

Laravel create route with variable

我试图在路由到我的控制器中的创建函数时传递一个变量。

<a href="{{ route('customercolors.create',$customer->id) }}" title="Add color" class="">Add color</a>

CustomerColorController.php

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

我只能通过编写自己的路线来解决这个问题,但事实并非如此:

<a href="{{ url('customercolor/add',$customer->id) }}" title="Add color" class="px-4 py-2 bg-gray-800 border border-transparent font-semibold text-xs text-white uppercase tracking-widest hover:bg-gray-700 active:bg-gray-900 focus:outline-none focus:border-gray-900 focus:ring ring-gray-300 disabled:opacity-25 transition ease-in-out duration-150">Add color</a>
                

Web.php

Route::get('/customercolor/add/{customer_id}', function ($customer_id) {
$colors = Color::get();
$customer = Customer::find($customer_id);
return view('customer_color.create', compact('customer', 'colors'));
});

 

如何使用指定的路由实现此目的?当我尝试明显更新时,我遇到了同样的问题。

很明显,正如评论中提到的,你把事情弄糊涂了。首先,您有一个从未在路由文件中使用过的控制器文件 - web.php。无意中,您正在使用 PHP 闭包来为您的视图提供服务。最后,您使用的是不存在的命名路由。

进行以下更改以使一切正常:

wep.php

<?php

use Illuminate\Support\Facade\Route;
use App\Http\Controllers\CustomerColorController; // path to your controller

Route::get('/customercolor/add/{customer}', [CustomerColorController::class, 'create'])->name('customercolors.create');

CustomerColorController.php

<?php

namespace App\Http\Controllers;

use App\Models\Customer;
use App\Models\Color;

class CustomerColorController extends Controller
{
    public function create(Customer $customer)
    {
        $colors = Color::all(); // assuming you want all color instances
        return view('customer_color.create')->with(['customer'=>$customer, 'colors'=>$colors]);
    }
}

在 Blade 模板中包含路由

<!-- make sure "$customer" is defined on this page -->
<a href="{{ route('customercolors.create', $customer->id) }}" title="" class="">Add Color</a>