Search code examples
laravellaravel-9

Laravel how to skip single field validation in update time


I have a common blade form for add and update

<form action={{  $bookEnt->id == null ?  route( "book-post" ) : route("book-update",['bookId'=>$bookEnt->id]) }} method = "POST" enctype="multipart/form-data">
    @csrf
    @method( $bookEnt->id == null ? 'post':'put')

    //blade fields 
</form>

I have created a request for validation the form request

public function rules()
{
        return [
            'title' => 'required|string',
            'file_pdf' => 'required|mimes:pdf|max:30720',
        ];
}

Below by add controller

public function add(\App\Http\Requests\BookFormRequest $request)
{   
        // todo : msg
        if( $request->isMethod('put') || $request->isMethod('post') )
        {
            $book = $bookId ? $this->getBookById($bookId):new Book;
            -----
        }
}

When the method is put how I will skip validation for 'file_pdf' ? I don't want to create another request class.


Solution

  • Use switch case and check request method type so:

    public function rules()
    {
        switch ($this->method()) {
    
            case 'POST':
    
                return [
                    'title' => 'required|string',
                    'file_pdf' => 'required|mimes:pdf|max:30720',
                ];
            case 'PUT':
                return [
                    'title' => 'required|string'
                ];
            default:
                return [];
    
        }
    }