Home > Back-end >  Laravel how to skip single field validation in update time
Laravel how to skip single field validation in update time

Time:01-11

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.

CodePudding user response:

use switch case and check request method type

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 [];

    }
}
  • Related