I am quite new to Laravel and have been reading the documentation on testing, however I am not sure how I would go about Unit Testing the Controller I have posted below. Any advice on how I would go about this is much appreciated.
The controller below is the CRUD controller I created for Booking Forms.
class BookingFormsController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$bookingforms = BookingForm::orderBy('surgeryDate', 'asc')->paginate(5);
return view('bookingforms.index')->with('bookingforms', $bookingforms);
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
return view('bookingforms.create');
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $booking)
{
$this->validate($booking, [
'requestID' => 'required',
'patientID' => 'required',
'patientForename' => 'required',
'patientSurname'=> 'required',
'patientSex' => 'required',
'patientDOB' => 'required',
'surgeryType' => 'required',
'surgeryDate' => 'required',
'performingSurgeon' => 'required',
'TheatreRoomID' => 'required',
'patientUrgency' => 'required',
'patientNotes' => 'required',
'bloodGroup' => 'required'
]);
// Create new Booking Form
$bookingform = new Bookingform;
$bookingform->requestID = $booking->input('requestID');
$bookingform->bookingID = $booking->input('bookingID');
$bookingform->patientID = $booking->input('patientID');
$bookingform->patientForename = $booking->input('patientForename');
$bookingform->patientSurname = $booking->input('patientSurname');
$bookingform->patientSex = $booking->input('patientSex');
$bookingform->patientDOB = $booking->input('patientDOB');
$bookingform->surgeryType = $booking->input('surgeryType');
$bookingform->surgeryDate = $booking->input('surgeryDate');
$bookingform->performingSurgeon = $booking->input('performingSurgeon');
$bookingform->TheatreRoomID = $booking->input('TheatreRoomID');
$bookingform->patientUrgency = $booking->input('patientUrgency');
$bookingform->patientNotes = $booking->input('patientNotes');
$bookingform->bloodGroup = $booking->input('bloodGroup');
$bookingform->user_id = auth()->user()->id;
//Save Booking form
$bookingform->save();
//redirect
return redirect('/bookingforms')->with('success', 'Booking Submitted');
}
/**
* Display the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function show($bookingID)
{
$bookingform = BookingForm::find($bookingID);
return view('bookingforms.show')->with('bookingform', $bookingform);
}
/**
* Show the form for editing the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function edit($bookingID)
{
$bookingform = BookingForm::find($bookingID);
//check for correct user_id
if(auth()->user()->id !==$bookingform->user_id){
return redirect('/bookingforms')->with('danger', 'This is not your booking, please contact the Booker.');
}
return view('bookingforms.edit')->with('bookingform', $bookingform);
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param int $id
* #return \Illuminate\Http\Response
*/
public function update(Request $booking, $bookingID)
{
$this->validate($booking, [
'patientID' => 'required',
'patientForename' => 'required',
'patientSurname'=> 'required',
'patientSex' => 'required',
'patientDOB' => 'required',
'surgeryType' => 'required',
'surgeryDate' => 'required',
'performingSurgeon' => 'required',
'TheatreRoomID' => 'required',
'patientUrgency' => 'required',
'patientNotes' => 'required',
'bloodGroup' => 'required'
]);
// Create new Booking Form
$bookingform = Bookingform::find($bookingID);
$bookingform->bookingID = $booking->input('bookingID');
$bookingform->patientID = $booking->input('patientID');
$bookingform->patientForename = $booking->input('patientForename');
$bookingform->patientSurname = $booking->input('patientSurname');
$bookingform->patientSex = $booking->input('patientSex');
$bookingform->patientDOB = $booking->input('patientDOB');
$bookingform->surgeryType = $booking->input('surgeryType');
$bookingform->surgeryDate = $booking->input('surgeryDate');
$bookingform->performingSurgeon = $booking->input('performingSurgeon');
$bookingform->TheatreRoomID = $booking->input('TheatreRoomID');
$bookingform->patientUrgency = $booking->input('patientUrgency');
$bookingform->patientNotes = $booking->input('patientNotes');
$bookingform->bloodGroup = $booking->input('bloodGroup');
$bookingform->user_id = auth()->user()->id;
//Save Booking form
$bookingform->save();
//redirect
return redirect('/bookingforms')->with('success', 'Booking Updated');
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function destroy($bookingID)
{
$bookingform = Bookingform::find($bookingID);
if(auth()->user()->id !==$bookingform->user_id){
return redirect('/bookingforms')->with('danger', 'This is not your booking, please contact the Booker.');
}
$bookingform->delete();
return redirect('/bookingforms')->with('success', 'Booking Removed');
}
A simple example:
class ExampleTest extends TestCase
{
public function testBookingFormsIndex()
{
$response = $this->get('index');
$response->assertStatus('200');
}
public function testBookingFormsCreate()
{
$response = $this->get('create');
$response->assertStatus('200');
}
}
Like i said, the above is a basic example that is based on the example from the HTTP Test documentation from laravel.
More information can be found here:
https://laravel.com/docs/7.x/http-tests
I would also recommend using the laravel Requests to validate your form inputs, this keeps your controller clean and places the code where is belongs.
More information on this topic can be found here: https://laravel.com/docs/7.x/validation#creating-form-requests
The controller you wrote is a bit hard to test, as it is tightly coupled to the Eloquent model. You would better decouple it by adding a repository layer and inject it into your controller.
BTW: you can use fillable attributes to avoid writing a lot of code just to fill the attributes of your BookingForm
Now for example you may do the following:
Create A BookingFormRepository interface:
interface BookingFormRepository
{
public function all();
public function create(array $attributes);
// etc ....
}
Create an implementation of the BookingFormRepository:
class BookingFormRepositoryImpl implements BookingRepository
{
public function all()
{
return BookingForm::all();
}
public function create(array $attributes)
{
// Use fillable attributes for better readability
$record = BookingForm::create($attributes);
return $record;
}
// Implement other methods ....
}
In the AppServiceProvider in the register method bind your implementation:
App::bind(BookingFormRepository::class, BookingFormRepositoryImpl::class);
Then in your controller, inject the BookingRepository interface:
class BookingFormController extends Controller {
private $bookingFormRepository;
public function __construct(BookingFormRepository $bookingRepo)
{
$this->bookingFormRepository = $bookingRepo;
}
public function index()
{
$bookings = $this->bookingFormRepository->all();
return view('bookingform.index', $bookings);
}
// .. other methods ... like `store`
}
Now the controller will be easy to test, just mock the BookingRepository and make call assertions on it:
class BookingFormControllerTest extends TestCase
{
public function testIndexBookingForm()
{
// Arrange
$repository = Mockery::mock('BookingRepository');
$repository->shouldReceive('all')->once()
->andReturn(['foobar']);
App::instance('BookingRepository', $repository);
// Act, Replace with your right url ...
$this->get('bookings');
// Assert
$this->assertResponseOk();
$this->assertViewHas('bookingforms.index', ['foobar']);
}
}
I recommand reading the Taylor Otwell book "Laravel from aprentice to Artisan".
Related
Every time I create a new book or update it with the same author, a new instance of the same author creates in DB
This is my codes here
Here is the BooksController
<?php
namespace App\Http\Controllers;
use App\Models\Author;
use App\Models\Book;
use Illuminate\Http\Request;
class BooksController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$books = Book::orderBy('created_at', 'desc')->with('authors')->paginate(5);
return view('books.index', [
'books' => $books
]);
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
return view('books.create');
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$request->validate([
'author_name' => 'required',
'title' => 'required',
'release_year' => 'required|numeric',
'status' => 'required',
]);
I think I need to check here
// check if author already exists..
$authors = Author::all();
foreach($authors as $a){
if($a->name == $request->input('author_name')){
$author = $a;
}else{
}
}
Here if I have Glukhovski in the database and create a new book with the same author, another Glukhovski is added in the database, so I think there must be a way to check and if the author already exists, assign it to the book through the pivot table?
$author = Author::create([
'name' => $request->input('author_name')
]);
$book = Book::create([
'title' => $request->input('title'),
'release_year' => $request->input('release_year'),
'status' => $request->input('status')
]);
$book->authors()->attach($author->id);
return redirect('/books');
}
/**
* Display the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function show($id)
{
$book = Book::find($id);
return view('books.show')->with('book', $book);
}
/**
* Show the form for editing the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function edit($id)
{
$book = Book::find($id);
return view('books.edit')->with('book', $book);
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param int $id
* #return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
$request->validate([
'author_name' => 'required',
'title' => 'required',
'release_year' => 'required',
'status' => 'required',
]);
... and here as well
// check if author already exists.....
//
$author = Author::create([
'name' => $request->input('author_name')
]);
$book = Book::find($id);
$book -> update([
'title' => $request->input('title'),
'release_year' => $request->input('release_year'),
'status' => $request->input('status')
]);
$book->authors()->sync($author->id);
return redirect('/books');
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function destroy($id)
{
Book::find($id)->delete();
return redirect('books');
}
}
Pivot table:
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateAuthorBookTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('author_book', function (Blueprint $table) {
$table->id();
$table->foreignId('author_id');
$table->foreignId('book_id');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('author_book');
}
}
you can check first for author in this way before you create the author, if author doesn't exist, it will create a new one
$author = Author::where('name',$request->input('author_name'))->first();
if(!$author){
$author = Author::create([
'name' => $request->input('author_name')
]);
}
I'm trying to send the form information to database but when i submit the form this error appears:
ErrorException
Declaration of App\Http\Controllers\LivroController::authorize() should be compatible with App\Http\Controllers\Controller::authorize($ability, $arguments = Array)
CONTROLLER (LivroController)
<?php
namespace App\Http\Controllers;
use App\Http\Requests\StoreUpdateLivro;
use Illuminate\Support\Facades\Auth;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\Livro;
class LivroController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
protected $request;
private $repository;
private $livro;
public function __construct(Livro $livro)
{
$this->livro = $livro;
}
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public function authorize()
{
return true;
}
/* public function index()*/
// {
/* $title = 'listagem dos livros';
$livros = $this->livro->all();
return view ('livros/cadastro', compact('livros','title'));*/
// return view ('livros/cadastro');
// }
protected function validator(Request $request)
{
return Validator::make($request, [
'namel' => ['required', 'string', 'max:200'],
'autor' => ['required', 'string', 'email', 'max:200'],
'editora' => ['required', 'string', 'max:50'],
'categoria'=> ['required', 'string', 'min:50'],
'classificação'=> ['required', 'string', 'min:1','max:2'],
'descricao'=> ['required', 'string', 'min:200'],
'image'=> ['not required'],
]);
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function create(StoreUpdateLivro $request)
{
$user = Auth::user()->id;
$data = $request->all();
if($request->image->isValid()){
$image = $request->image->store('livros');
$data['image'] = $image;
}
Livro::create([
'users_id' => $user,
'namel' => $request['namel'],
'autor' => $request['autor'],
'editora' => $request['editora'],
'categoria'=> $request['categoria'],
'classificação'=>$request['classificação'] ,
'descricao'=>$request['descricao'],
'image'=>$request['image'],
]);
return view('livros/cadastro');
}
public function index()
{
$livro = DB::select('select * from livros');
return view('livros/mostrar_livros', [
'livro' => $livro,
]);
}
}
Remove authorize() method from LivroController and then,
go to StoreUpdateLivro file and set return true into authorize() method.
and also you don't need to validator method in your controller.
See more about the FormRequest in Laravel.
I think, you have a copy/paste problem
Delete LivroController:: authorize() method - you copied it from Form Request - and all will be work fine.
I have reviewed similar questions but none of the solutions worked for me. I have show view that fetches data from the db which I want to display. I believe I have the right code for my show function on my CtnController but I keep getting this frustrating error. Ctn in this case is a type of form I'm trying to create.
This is my controller.
<?php
namespace App\Http\Controllers;
use App\Ctn;
use Illuminate\Http\Request;
class CtnController extends Controller
{
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('auth');
}
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$ctns = Ctn::orderBy('created_at', 'desc')->paginate(5);
return view('/ctn.index')->with('ctns', $ctns);
}
public function create(){
return view('/ctn.create');
}
public function store(Request $request){
$validatedData = $request -> validate([
'bol' => 'required',
'carrier' => 'required',
'address' => 'required',
'etd' => 'required',
'eta' => 'required',
'portload' => 'required',
'portdischarge' => 'required',
]);
$ctn = new Ctn;
$ctn->bill_landing = request('bol');
$ctn->carrier = request('carrier');
$ctn->address = request('address');
$ctn->eta = request('eta');
$ctn->etd = request('etd');
$ctn->incoterm = request('incoterm');
$ctn->forwarder = request('forwarder');
$ctn->ctnref = request('ctnref');
$ctn->portloading = request('portload');
$ctn->portdischarge = request('portdischarge');
$ctn->quantity = request('quantity');
$ctn->origin_goods = request('origin');
$ctn->cost_goods = request('cost');
$ctn->currency = request('currency');
$ctn->package_type = request('package');
$ctn->save();
return redirect('/ctn')->with('success', 'CTN created');
}
/**
* Display the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function show($id)
{
$ctn = Ctn::find($id);
return view('/ctn.show', compact('ctn'));
}
}
Below is my show route on web.php file
Route::get('/ctn/show', 'CtnController#show')->name('show');
The show form is just a HTML form.
Your show() method excepts an $id, however, you've not specified the value in your route. Change your route definition so that is can accept the id:
Route::get('/ctn/show/{id}', 'CtnController#show')->name('show');
This will assume that you're using a url like:
http://example.com/ctn/show/1
For more information you can view the Route Parameters documentation
The $id argument of your show method expects an implicit binding from the route parameters, but your routes does not know any id parameter, therefore it can't be bound to your method.
I have a question about showing posts from specific user. I'm building a basic keeping records website for my brothers company. I made a redirected login for normal users(workers in company) and for admin(company manager). So I'm new at Laravel and programming, a did everything for this website and all I need is how to show posts on admin profile for specific user. On admin profile I'll make pages for all workers profiles and on specific page I need to show posts for that specific user. How can I do that? Making new Controller?
<?php
namespace App\Http\Controllers;
use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;
use App\Post;
class PostsController extends Controller
{
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('auth');
}
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$post = Post::all();
return view('posts.tabela')->with('posts', $post);
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
return view('posts.create');
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$this->validate($request, [
'br_kesice' => 'required',
'ime' => 'required',
'br_telefona' => 'required',
'posao' => 'required',
'cijena' => 'required',
'placanje' => 'required',
'popust' => 'required',
'datum_preuz' => 'required',
'datum_izdav' => 'required',
'smjena' => 'required',
'radnik' => 'required',
'status' => 'required'
]);
$post = new Post;
$post->br_kesice = $request->input('br_kesice');
$post->ime = $request->input('ime');
$post->br_telefona = $request->input('br_telefona');
$post->posao = $request->input('posao');
$post->cijena = $request->input('cijena');
$post->placanje = $request->input('placanje');
$post->popust = $request->input('popust');
$post->datum_preuz = $request->input('datum_preuz');
$post->datum_izdav = $request->input('datum_izdav');
$post->smjena = $request->input('smjena');
$post->radnik = $request->input('radnik');
$post->status = $request->input('status');
$post->user_id = auth()->user()->id;
$post->save();
return redirect('/home');
}
/**
* Display the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function show($id)
{
//
}
/**
* Show the form for editing the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function edit($id)
{
$post = Post::find($id);
if(auth()->user()->id !==$post->user_id){
return redirect('/posts')->with('error', 'Nedozvoljen pristup!');
}
return view('posts.edit', compact('post', 'id'))->with('post', $post);
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param int $id
* #return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
$this->validate($request, [
'br_kesice' => 'required',
'ime' => 'required',
'br_telefona' => 'required',
'posao' => 'required',
'cijena' => 'required',
'placanje' => 'required',
'popust' => 'required',
'datum_preuz' => 'required',
'smjena' => 'required',
'radnik' => 'required',
'status' => 'required'
]);
$post = Post::find($id);
$post->br_kesice = $request->input('br_kesice');
$post->ime = $request->input('ime');
$post->br_telefona = $request->input('br_telefona');
$post->posao = $request->input('posao');
$post->cijena = $request->input('cijena');
$post->placanje = $request->input('placanje');
$post->popust = $request->input('popust');
$post->datum_preuz = $request->input('datum_preuz');
$post->datum_izdav = $request->input('datum_izdav');
$post->smjena = $request->input('smjena');
$post->radnik = $request->input('radnik');
$post->status = $request->input('status');
$post->save();
return redirect('/home');
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function destroy($id)
{
//
}
}
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use App\User;
class Post extends Model
{
protected $table = 'posts';
public $primaryKey = 'id';
public $timestamps = true;
public function user(){
return $this->belongsTo('App\User');
}
}
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use App\Post;
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
public function posts(){
return $this->hasMany('App\Post');
}
public function is_admin(){
if($this->admin)
{
return true;
}
return false;
}
}
I would like to ask how should I handle validation on multiple scenarios using FormRequest in L5? I know and I was told that I can create saparate FormRequest files to handle different validations but it is very redundant and also noted that I would need to inject it into the controller manually using the use FormRequest; keyword. What did previously in L4.2 is that I can define a new function inside my customValidator.php which then being called during controller validation via trycatch and then the data is being validated by service using the below implementation.
class somethingFormValidator extends \Core\Validators\LaravelValidator
{
protected $rules = array(
'title' => 'required',
'fullname' => 'required',
// and many more
);
public function scenario($scene)
{
switch ($scene) {
case 'update':
$this->rules = array(
'title' => 'required',
'fullname' => 'required',
// and other update validated inputs
break;
}
return $this;
}
}
Which then in my LaravelValidator.php
<?php namespace Core\Validators;
use Validator;
abstract class LaravelValidator {
/**
* Validator
*
* #var \Illuminate\Validation\Factory
*/
protected $validator;
/**
* Validation data key => value array
*
* #var Array
*/
protected $data = array();
/**
* Validation errors
*
* #var Array
*/
protected $errors = array();
/**
* Validation rules
*
* #var Array
*/
protected $rules = array();
/**
* Custom validation messages
*
* #var Array
*/
protected $messages = array();
public function __construct(Validator $validator)
{
$this->validator = $validator;
}
/**
* Set data to validate
*
* #return \Services\Validations\AbstractLaravelValidator
*/
public function with(array $data)
{
$this->data = $data;
return $this;
}
/**
* Validation passes or fails
*
* #return Boolean
*/
public function passes()
{
$validator = Validator::make(
$this->data,
$this->rules,
$this->messages
);
if ($validator->fails())
{
$this->errors = $validator->messages();
return false;
}
return true;
}
/**
* Return errors, if any
*
* #return array
*/
public function errors()
{
return $this->errors;
}
}
and then finally this is how i call the scenarios inside services like this
public function __construct(somethingFormValidator $v)
{
$this->v = $v;
}
public function updateSomething($array)
{
if($this->v->scenario('update')->with($array)->passes())
{
//do something
else
{
throw new ValidationFailedException(
'Validation Fail',
null,
$this->v->errors()
);
}
}
So the problem is now since i have migrated to L5 and L5 uses FormRequest, how should I use scenario validation in my codes?
<?php namespace App\Http\Requests;
use App\Http\Requests\Request;
class ResetpasswordRequest extends Request {
/**
* 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
*/
public function rules()
{
return [
'login_email' => 'required',
'g-recaptcha-response' => 'required|captcha',
];
}
public function messages()
{
return [
'login_email.required' => 'Email cannot be blank',
'g-recaptcha-response.required' => 'Are you a robot?',
'g-recaptcha-response.captcha' => 'Captcha session timeout'
];
}
public function scenario($scene)
{
switch ($scene) {
case 'scene1':
$this->rules = array(
//scenario rules
);
break;
}
return $this;
}
}
also how should I call it in the controller?
public function postReset(ResetpasswordRequest $request)
{
$profile = ProfileService::getProfileByEmail(Request::input('login_email'));
if($profile == null)
{
$e = array('login_email' => 'This email address is not registered');
return redirect()->route('reset')->withInput()->withErrors($e);
}
else
{
//$hash = ProfileService::createResetHash($profile->profile_id);
$time = strtotime('now');
$ip = Determinator::getClientIP();
MailProcessor::sendResetEmail(array('email' => $profile->email,
'ip' => $ip, 'time' => $time,));
}
}
I believe the real issue at hand is everything is validated through the form request object before it reaches your controller and you were unable to set the appropriate validation rules.
The best solution I can come up with for that is to set the validation rules in the form request object's constructor. Unfortunately, I am not sure how or where you are able to come up with the $scene var as it seems to be hard-coded in your example as 'update'.
I did come up with this though. Hopefully reading my comments in the constructor will help further.
namespace App\Http\Requests;
use App\Http\Requests\Request;
class TestFormRequest extends Request
{
protected $rules = [
'title' => 'required',
'fullname' => 'required',
// and many more
];
public function __construct()
{
call_user_func_array(array($this, 'parent::__construct'), func_get_args());
// Not sure how to come up with the scenario. It would be easiest to add/set a hidden form field
// and set it to 'scene1' etc...
$this->scenario($this->get('scenario'));
// Could also inspect the route to set the correct scenario if that would be helpful?
// $this->route()->getUri();
}
/**
* 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
*/
public function rules()
{
return $this->rules;
}
public function scenario($scene)
{
switch ($scene) {
case 'scene1':
$this->rules = [
//scenario rules
];
break;
}
}
}
You can use laratalks/validator package for validation with multiple scenarios in laravel. see this repo