How to get current value in Laravel form request for array field?

Updated: Feb 03, 2025

How to get current value in Laravel form request for array field?

To get the current value of an array field in a Laravel form request, you can access the $request object within the request class and use the get() method to retrieve the value of the specific array key. Here's a step-by-step guide on how to do it:

  1. Define the form request class:

First, you need to define a form request class that extends the Illuminate\Foundation\Http\FormRequest class. This class will be used to validate and sanitize the incoming request data.

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class UpdateUserRequest extends FormRequest
{
    // ...
}
  1. Define the rules:

Next, define the rules for the array field in the rules() method of the request class.

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class UpdateUserRequest extends FormRequest
{
    public function rules()
    {
        return [
            'name' => 'required|string|max:255',
            'email' => 'required|string|email|max:255|unique:users,email,'.$this->route('id'),
            'roles' => 'array',
        ];
    }

    // ...
}

In this example, the roles field is defined as an array.

  1. Get the current value:

To get the current value of the roles array field, you can use the get() method of the $request object within the request class.

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class UpdateUserRequest extends FormRequest
{
    public function rules()
    {
        return [
            'name' => 'required|string|max:255',
            'email' => 'required|string|email|max:255|unique:users,email,'.$this->route('id'),
            'roles' => 'array',
        ];
    }

    public function getCurrentRoles()
    {
        return $this->request->get('roles');
    }

    // ...
}

In this example, we've defined a new method called getCurrentRoles() that returns the current value of the roles array field.

  1. Use the method in your controller:

Finally, you can use the getCurrentRoles() method in your controller to get the current value of the roles array field.

namespace App\Http\Controllers;

use App\Http\Requests\UpdateUserRequest;
use App\Models\User;

class UserController extends Controller
{
    public function update(UpdateUserRequest $request, User $user)
    {
        $roles = $request->getCurrentRoles();

        // ...
    }
}

In this example, we've injected the UpdateUserRequest instance and the User model into the update() method of the controller. We then call the getCurrentRoles() method to get the current value of the roles array field.

That's it! You now know how to get the current value of an array field in a Laravel form request.