Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel Update Syntax - Updating Record with Array

I'm having trouble doing a basic record update via POST in Laravel.

I have captured all the post data in an array, and if the existing Order# is 0, then I create a new record (works fine). Otherwise I update the existing record.

Order.php

class Order extends Eloquent {
    public static $table = 'my_orders';
}

Routes.php

//Handle a new order POST
Route::post('order', array('do' => function() {
    $thisOrder = array(
         'qty' => Input::get('quantity'),
         'desc' => Input::get('description'),
    );

    $thisOrderID = Input::get('orderNo');

    //CHECK FOR NEW OR EXISTING ORDER
    if($thisOrderID > 0) {
        //THIS FUNCTION SOMEHOW RETURNS THE FUNCTION CALL AND DOESNT CONTINUE PAST
        //AND THE RECORD IS NOT UPDATED
        $updateOrder = Order::update($thisOrderID, $thisOrder);
    }
}

Update: The code above does in fact work. I had a validation error, which was causing the function to return early.

like image 388
jamis0n Avatar asked Dec 03 '12 14:12

jamis0n


3 Answers

Instead of this line:

$updateOrder = Order::update($thisOrderID, $thisOrder);

You need to do:

$updateOrder = Order::find($thisOrderID)->update($thisOrder);

With find() (which equals where_id()) you select a specific row from the database and with update you pass the new data.

like image 151
markvaneijk Avatar answered Nov 07 '22 21:11

markvaneijk


What do you think of this:

//Handle a new order POST
Route::post('order', array('do' => function() {
    $thisOrder = array(
         'qty' => Input::get('quantity'),
         'desc' => Input::get('description'),
    );

    $thisOrderID = Input::get('orderNo');

    $order = Order::find( $thisOrderID );

    //CHECK FOR NEW OR EXISTING ORDER
    if( $order ) {
        $order->title = 'New order title';
        $order->desc = 'New description';
        $order->save();
    }
}
like image 3
ceesvanegmond Avatar answered Nov 07 '22 22:11

ceesvanegmond


erm , I will suggest to do it this way, if $thisOrder include the key, it will just update the record, else it will just create a new record.

$thisOrder = array(
     'orderNo' => Input::get('orderNo'),
     'qty' => Input::get('quantity'),
     'desc' => Input::get('description'),
);

$updateOrder = Order::save($thisOrder);

if Input::get('orderNo') no value will be create else update

like image 2
Knight Avatar answered Nov 07 '22 21:11

Knight