D
D
Div-Man2018-12-25 20:16:42
Laravel
Div-Man, 2018-12-25 20:16:42

What is the best way to shorten the method, the controller, so that it would be easier to test it?

Now here is such a bold method

public function store(Request $request)
    {
       $rules = [
           'description' => 'min:4',
           'image' => 'required|image|mimes:jpg,jpeg,png',
           'choose-category' => 'array|required'
           ];
    
        $messages = [
            'description.min' => 'Название должно содержать минимум :min символа.',
            'image.required' => 'Изображение загружать обязательно.',
            'image.image' => 'Вы загрузили не изображение.',
            'image.mimes' => 'Допустимые форматы: jpg, jpeg, png.',
            'choose-category.required' => 'Выберите категорию'
         ];
    
        Validator::make(
            $request->all(), 
            $rules ,
            $messages
              )->validate(); 
     
      $image = $request->file('image');
      
      $description = $request->input('description');
      
      $this->imageClass->add($image, $description);
  
      $this->imageClass->save();

      $idNewImage = $this->imageClass->id;
      $categories = $request->input('choose-category');
      
      $relation = \App\Services\Image::find($idNewImage);
        
      $relation->categories()->attach($categories);
      
      return redirect('/');
    }

Should the validation be put into the model and only tested if it was successful or not?
For example, in the controller would be
$validation = this->imageClass->validation($request->all());

But what about the rest of the code, and leave it like that?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
V
Vasyl Fomin, 2018-12-25
@fomvasss

https://laravel.ru/posts/864 - not a direct answer to your question, but a good article not on this topic

A
Anton, 2018-12-25
@Yadalay

Move validation into a separate request - https://laravel.com/docs/5.7/validation#creating-f...

J
jazzus, 2018-12-26
@jazzus

Yes, validation in separate files is very convenient
php artisan make:request FileRequest
and transfer the rules and messages there, and connect it in the controller via use and use it in the method (FileRequest $request). The rest of the code is great)) You can also add variable checks, for example, if($relation)... etc. to eliminate errors, add also access rights to the method and, of course, connect json upload for js

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question