mardi 20 novembre 2018

How to test laravel controller method?

My controller looks like this:

public function store(Request $request) {

        $validateData = $request->validate([
            'name' => 'required|unique:languages',
            'code' => 'required|size:3',
            'flag' => 'required|size:2'
        ]);

        $language = new Language();
        $language->name = $request->name;
        $language->code = $request->code;
        $language->flag = $request->flag;
        $saveLanguage = $language->save();

        if(!$saveLanguage){
            return response()->json(['error'=>'Something went wrong, please try later.'],500);
        }

        return response()->json(['success'=>'Language has been created successfully', 'data'=>$language],200);

As you can see, I am instantiate new Language object and everything works fine, but first problem is imagine if I change Language class in future (for example: you have to pass 2 parameters in constructor), I have to change this controller and every other controllers where I am instantiating Language object.

The second problem is I can't or it's too hard to test this controller.

I am curious what is the best solution to solve this problems in laravel?

For example is it a good solution to use simple factory or factory method pattern for every model I am using in my controllers.

Aucun commentaire:

Enregistrer un commentaire