Home > OS >  Laravel create route with variable
Laravel create route with variable

Time:03-22

I'm trying to pass a variable while routing to the create function in my controller.

<a href="{{ route('customercolors.create',$customer->id) }}" title="Add color" >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');
}
        

I can only solve this by writing my own route but this is not how it should be:

<a href="{{ url('customercolor/add',$customer->id) }}" title="Add color" >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'));
});

 

How do I achieve this with the specified routes? I'm having the same issue when I try to update obviously.

CodePudding user response:

Obviously, as mentioned in the comments you have things muddled up. First, you have a controller file that's never used in your route file - web.php. Inadvertently, you are using PHP closure to serve your view. Finally, you are using a named route that doesn't exist.

Make the following changes to get things working:

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]);
    }
}

Including route in Blade template

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