Thursday 23 August 2018

Separating Routes In Node.js Express 4


If you prefer using the Query builder in Laravel instead of Eloquent, I'm on your side: D because I also use the query Builder for most Query activities in my Laravel Application.


Well, usually the Coding default from birth might be: D, when the Insert, Update, Delete query might be something like this


public function doUpdate ($ data) {


    $ data = array (

     'name' => $ data ['name'],

     'alamar' => $ data ['alamar']

    );


    // auth :: user () -> id: session logged user

    $ update = DB :: table ('user') -> where ('user_id', Auth :: user () -> id)

                                  -> update ($ data);

    if ($ update)

        return Redirect :: to ('user / profile');

     else

        // blablaa ...

}

or like this


public function doUpdate ($ data) {


    $ data = array (

     'name' => $ data ['name'],

     'alamar' => $ data ['alamar']

    );


    // auth :: user () -> id: session logged user

    $ update = DB :: table ('user') -> where ('user_id', Auth :: user () -> id)

                                  -> update ($ data);

    if (! $ update) {


        // redirect with error

        return Redirect :: to ('user / profile') -> with ('error_update', true);

    

     }

     else

       return Redirect :: to ('user / profile');

}

To Update, Delete uses the query builder in laravel, the return is in the form of Affected rows. so the query above is not right and can cause problems.


We can simply handle this as well


public function doUpdate ($ data) {


    $ data = array (

     'name' => $ data ['name'],

     'alamar' => $ data ['alamar']

    );


    // auth :: user () -> id: session logged user


    try {


        DB :: table ('user') -> where ('user_id', Auth :: user () -> id) -> update ($ data);


    } catch (\ Exception $ e) {


        // The log will be stored in STorage / logs / laravel.log

        Log :: error ('Can not process update:'. $ E-> getMessage ());

        // redirect with Error

        return Redirect :: to ('user / profile') -> with ('error_update', true);

   }


   // redirect success

   return Redirect :: to ('user / profile') -> with ('success_update', true);

  

}

with try catch we can determine when our query is successful or not


CMIIW

Share this


0 Comments