laravel 9 foreign key validation example

in this section we will see how to validate foreign key in laravel 9. For this section we will See Blog or Posts have category_id foreign key. Also we will see laravel 9 validate Foreign Key with custom error message.


Example 1

Simple category_id foreign key validation checking exists in categories table.

$request->validate([
    'category_id' => 'required|exists:categories,id'
]);



Example 2

Laravel 9 Using Category Modal class name to validate Foreign Key.

$request->validate([
    'category_id' => 'required|exists:App\Models\Category,id'
]);
laravel 9 validation foreign key

laravel 9 validation foreign key


Example 3

Laravel 9 validate Foreign Key with custom error message.

$request->validate([
    'category_id' => 'required|exists:App\Models\Category,id',
    ],
    [
    'category_id.exists' => 'Given Category_id is Not an existing ID',
    ]);
Laravel 9 foreign key custom error message

Laravel 9 foreign key custom error message


Example 4

Using laravel 9 custom Rule to validation Foreign key.

Create post or blog request to add validation Foreign key validation.

php artisan make:request PostStoreRequest

app/Http/Requests/PostStoreRequest.php

<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;

class PostStoreRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array<string, mixed>
     */
    public function rules()
    {
        return [
            'category_id' => ['required', Rule::exists('categories', 'id')]
        ];
    }
}


Now Add app/Http/Requests/PostStoreRequest.php in PostController.php

public function store(PostStoreRequest $request)
{
    $validated = $request->validated();
}