0
votes

I decided to move from CI to laravel, and I'm having some trouble understanding the correct implementation of a basic form that inserts into a db, then loads the records. My form calls my controller method, which handles the input data and saves it, but I feel like I should be using a model instead to handle this. Here is my code:

Routes.php

Route::get('neworder', 'HomeController@neworder');

Route::post('submitorder', 'HomeController@submitorder');

HomeController.php

public function neworder()
{
    return View::make('neworder');
}
public function submitorder()
{
    $order = new Order;
    $order->name = Input::get('name');
    $order->email = Input::get('email');
    $order->save();
    $orders = Order::all();
    return View::make('orders')->with('orders', $orders);

}

neworder.blade.php

@extends('layout')
@section('content')
    {{ Form::open(array('action' => 'HomeController@submitorder')) }}
    <?php
    echo Form::text('email');
    echo Form::text('name');
    echo Form::submit('Submit');
    ?>
    {{ Form::close() }}
@stop
1
This may help you to understand but don't bind yourself to roles blindly. - The Alpha

1 Answers

0
votes

It sounds like what you have is working, which is great. There are a few improvements you can make, though.

One of them is to implement the repository pattern, which would change the code in your controller to something like this:

public function submitorder()
{
    if($this->_orderRepository->save(Input::all()) {
        $orders = $this->_orderRepository->all();
        return View::make('orders')->with('orders', $orders);
    } else {
        return View::make('orders')->with('errors', $this->_orderRepository->errors());
    }
}

The code above assumes that the validation logic lives inside of the order repository. This is acceptable, but goes against the single responsibility principle; your repository should only know how to create/retrieve/update entities in your database. Validation can instead live inside of a validator service

If you do implement a validation service, it wouldn't have too much impact on the submitorder function above (instead of $this->_orderRepository->save you would be calling $this->_orderForm->save), which is a great sign. It keeps the logic inside of the controller succint, any changes you make to the order model by adding fields have absolutely zero impact on your controller, and you're in a much better place emotionally because you aren't staying up at night worried that your stuff is going to break.