skip to Main Content

I am quite new to laravel. Using Laravel 8. When saving data I have seen below method in many examples.

In the controller

$emp = new Employee();
$emp->emp_name = $request->emp_name;
$emp->emp_no = $request->emp_no;
$emp->email = $request->email;
$emp->save();

My doubt is according to MVC principles controller is used to connect model and the view. Is this is a correct practice or have to do this part in the model ?

I am looking for some guidance to learn the best practice.

2

Answers


  1. In the MVC architecture, the model layer is responsible for managing the data, which includes tasks like validating, storing, and retrieving data. The controller layer handles the user’s input and controls the flow of the application, while the view layer is responsible for rendering the UI to the user.

    In the code you provided, the controller is creating a new instance of the Employee model, setting its properties, and then calling the save method to persist the data to the database. This is a common practice in Laravel, and it’s perfectly acceptable to do so.

    However, to strictly adhere to the MVC principles, the logic for persisting the data should ideally be placed in the model layer. You can create a method in the Employee model that accepts an array of data and handles the saving process. This way, the controller only needs to pass the data to the model, and the model takes care of the rest.

    In the controller

    $emp = new Employee();
    $emp->saveEmployee($request->all());
    

    In the model

    class Employee extends Model
    {
        protected $fillable = ['emp_name', 'emp_no', 'email'];
    
        public function saveEmployee($data)
        {
            $this->fill($data);
            $this->save();
        }
    }
    

    In this refactored code, the controller is simply passing the request data to the saveEmployee method in the model, and the model takes care of saving the data to the database.

    This approach keeps the model responsible for managing the data, and the controller simply acts as a mediator between the model and the view. It’s a good practice to follow as it makes your code more organized, easier to maintain, and adheres to the MVC principles.

    Login or Signup to reply.
  2. You can try following way as well:

    Model

    class Employee extends Model
    {
        protected $fillable = ['emp_name', 'emp_no', 'email'];
    }
    
    
    $emp = Employee::create($request->all()); // generally i avoid this way
    $emp = Employee::create($request->only(['emp_name', 'emp_no', 'email']));
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search