John Davidson

php - Laravel 8, how to pass form values to Route

0 comments
Message:


I am doing roles&permissions, an action that admin can change user to staff. I am able to send id to editRolePermission function, but the role value.


    function editRolePermission($id, "role value here")
{

$row = DB::table('users')
->where('id',$id)
->limit(1)
->update(array('role' => ''));
return redirect()->back();
}

<form action="{{ route('updateRolePermission', $user->id) }}" method="POST">

@method('PATCH')
@csrf

<select name="roles">
<option name ="user" value="user">User</option>
<option name= "staff" value="staff">Staff</option>
</select>
<input type="submit" onchange="this.form.submit()">
</form>

Route::patch('edit-role-permission/{id}', [AdminController::class, 'editRolePermission'])->name('updateRolePermission');


My Answer:
In Laravel 8, you can pass form values to a route by using the `Route::post` method in your `web.php` file. Here's an example of how you can pass form values to a route:

1. Create a form in your Blade view file (`resources/views/form.blade.php`) with the necessary input fields:

html

@csrf






2. Define the route in your `web.php` file (`routes/web.php`) to handle the form submission:

php
use Illuminate\Support\Facades\Route;

Route::post('/submit-form', function (Illuminate\Http\Request $request) {
$name = $request->input('name');
$email = $request->input('email');

// Do something with the form values (e.g. save to database)

return redirect()->back()->with('success', 'Form submitted successfully!');
})->name('submitForm');


3. In the above code, we are using the `Route::post` method to handle the form submission. We are retrieving the form values using the `input` method on the `$request` object. You can then perform any necessary actions with the form values (e.g. save to a database) and redirect the user back to the form with a success message.

4. You can also add validation to the form values by using Laravel's validation rules. For example, you can add the following code before processing the form values:

php
$request->validate([
'name' => 'required|string',
'email' => 'required|email',
]);


This will ensure that the `name` and `email` fields are required and have the correct format before processing the form values.

That's it! You have now successfully passed form values to a route in Laravel 8.

Rate this post

5 of 5 based on 5889 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us