简体   繁体   中英

How to save database operation in laravel

Thanks for watching my first question.
I have something confused.
How could I write the operations of database into database and don't write the function in every Controller?
I have considered middleware and find that must change my route register style.
my Route is this:

Route:resource('province','\\Modules\\Info\\Controllers\\P_ProvinceController');

Dose it has some awesome methods replace this?

 public function Store(Request $request)
        {
            $params = $request->input('data');
            $params['CreateID'] = Auth::user()->id;
            $params['CreateName'] = Auth::user()->name;
            $params['CreateTime'] = Carbon::now();
            $province = P_ProvinceModel::Create($params);
            $params['Pro_Is_Del'] = 1;
            $log_info['table'] = $province->getTable();
            $log_info['type']  = "create";
            $log_info['user']  = Auth::user()->name;
            $log_info['datetime'] =  Carbon::now();
            LogModel::create($log_info);
            if($province){
                return response()->json(array(
                    'status' => 200,
                    'msg' => '新增成功',
                    'data' => $province
                ));
            }else
                return response()->json(array(
                    'status' => 500,
                    'msg' => '保存失败',
                ));

        }

Thanks.

Here is how I solved across model functionality

First Create a Trait that does what you want on save.

<?php

namespace App\Models\Observers;

trait CreatedByObserver
{
    public static function bootCreatedByObserver(){
        /** Simply means that whenever this model is creating a model do: */
        static::creating(function($model){
            if(auth()->check()){
                 $responsiblePerson = auth()->user()->first_name . " " . auth()->user()->last_name;
            } else {
                 $responsiblePerson = "system";
            }
            /** You can set any model variables within */
            $model->created_by = $responsiblePerson;
        });
    }
}

In there do all you need to do when a record is saved/created/updated/deleted

Then In all Models you want this behaviour used add the trait.

Check them out here : https://laravel.com/docs/5.2/eloquent#events

As far i understand your question, you are asking for way to make your controller an abstract type, ie controller just need to handle the route and view not any other things(like database,application logic etc) which is the philosophy of the laravel Framework.

To make your controller abstract (meaning of abstract as explained aboave), first you need to understand, "What your application logic are and what your database logic are ?" when you understand these two things then, you can easily separate your aapplication logic and databasse logic from your controller.

For example : For keeping your Application logic you can make service folder in your root of your project also you can make folder name 'Dao' (Database access object) in the same path of service . You need to keep these folder in autoload from your composer. Just make class for service and your Dao.

And now your application follow will be, First Route, will hit controller then controller will need to call some method in service and then service will call the respective DAO . method.

Example :

Controller/YourController.php

Class YourController extends Controller {

 public function Store(Request $request,yourservice,$yourService)
        {
        $this->myservice = $yourservice;
        $this->myservice->store('your inputs request');
return $something ;
}


}

service/yourService.php

    Class yourService {

    public function store($yourinputs,yourDao $mydao){

     $this->mydao = $mydao;

//you can use your application logic here 
    return $this->mydao->create($yourinputs);
    }

And now the turn is for DAO :

dao/yourdao.php

use model // use your model here .
    class yourDao {
       public function create($yourdata,yourmodel $model){
       $this->model = $model;
      return $this->model->create($yourdata);

}
    }

Now, you can see the controller just save the data in database, but don't know how it is saving the data and what are the application logic. This explanation is just a simple way of doing project to make a controller abstract. There are other various ways of doing this. For example you can see Repository Design Pattern , which also used by laravel core .

Hope this explanation will not bore anyone . :) Happy coding .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM