简体   繁体   English

Laravel-使用控制器

[英]Laravel - Using Controllers

I am using laravel 5.4 and there is one thing i cant understand compeletely. 我正在使用laravel 5.4,有一件事我无法完全理解。 I have used make:controller (name) -resource to create a controller with index/show/create/edit/update/destroy. 我使用了make:controller(name)-resource来创建带有index / show / create / edit / update / destroy的控制器。 The app i am making is mostly CRUD operations. 我正在制作的应用主要是CRUD操作。 My question is : 我的问题是:

I must have a separate controller for every entity of my database that needs CRUD operations? 对于数据库中需要CRUD操作的每个实体,我必须有一个单独的控制器吗? For example i have 2 entities : Items, Services. 例如,我有2个实体:项目,服务。 I must have 2 controllers or they can be on the same controller like : 我必须有2个控制器,否则它们可以在同一控制器上,例如:

public function store_item(Request $request) {
            **Insert Query**
   }


public function store_service(Request $request) {
            **Insert Query**
   }

What is the correct way to do this? 正确的方法是什么?

They can be in the same Controller, but It is Good Practice to Create Different Controller for Items, Services or any CRUD Operations when it comes to Laravel. 它们可以在同一控制器中,但是当涉及Laravel时,为项目,服务或任何CRUD操作创建不同的控制器是一个好习惯。

In can you just want to create one Controller for both Items and Services, you have to make Functions like store_item and store_service And you have to call them With Every route Like Route::post('items','YourController@store_item'); 您可以只为商品和服务创建一个控制器,就必须创建诸如store_itemstore_service类的store_item ,并且必须通过诸如Route::post('items','YourController@store_item');每条路线来调用它们Route::post('items','YourController@store_item'); and Similar for Service. 和类似的服务。

But if you create Separate Controllers for Items and Services , You Don't have to create Route for Every Task or Action. 但是,如果您为ItemsServices创建单独的控制器,则不必为每个任务或动作创建路由。 You can just Register Resourceful Route in Your Routes File and you are good to go! 您只需要在Routes文件中注册Resourceful Route ,就可以了!

For example, If you are creating Separate Controllers for both Items and Services, You can just write these two Lines in your Routes File and you are good to go! 例如,如果要同时为项和服务创建单独的控制器,则只需将这两行写在Routes文件中就可以了!

Route::resource('items', 'ItemsController');
Route::resource('services', 'ServicesController');

So, It's good to Create Controller for CRUD operations because it makes stuff Neat and Clean in Laravel. 因此,为CRUD操作创建控制器是一件好事,因为它使Laravel中的内容变得整洁。 Let me know if you have any more queries! 让我知道您是否还有其他疑问!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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