在Laravel中使用多个控制器和模型的最佳方法是什么?

时间:2019-03-30 19:23:10

标签: laravel controller request

我有一个包含多个控制器和模型的项目。例如,表产品中有一个名为“ child ”的表 (产品的详细信息) ”。

在前端,用户创建一个新产品,但是该产品至少必须包含一个细节。当用户按下“创建产品”时,请求将附带产品信息(产品)和详细信息产品( producto_material )。

此刻我具有下一个结构:

  • 控制器(ProductoController,ProductoMaterialController)
  • 模型(ProductoModel,ProductoMaterialModel)

我希望每个控制器都通过自己的验证来照顾您,但请求将发送到ProductController。

网络路线:

Route::resource('products', 'ProductoController');
Route::get('duplicar/{param?}', 'ProductoExtController@duplicar');
Route::post('mostrarProductos', 'ProductoExtController@mostrarProductos');
Route::post('guardarValoresEditados', 'ProductoExtController@guardarValoresEditados');
Route::get('imprimirListadoPrecios', 'ProductoExtController@imprimirListadoPrecios');
Route::post('mostrarProductosStickers', 'ProductoExtController@mostrarProductosStickers');
Route::post('imprimirStickers','ProductoExtController@imprimirStickers');

产品负责人:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Modelos\ProductsModel;
use App\Modelos\ProductoMaterialModel;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Arr;
use App\Http\Requests\ProductoValidationRules;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Auth;


class ProductoController extends Controller
{

    protected $proMaterialesProducto;

    public function __construct(ProductoMaterialController $pMaterialesProducto)
    {
        $this->proMaterialesProducto = $pMaterialesProducto;
    }

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        if (\Gate::allows('isAdmin') || \Gate::allows('isUser')){
            return ProductsModel::latest()
                        ->orderBy('created_at','desc')
                        ->paginate(10);
        }
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(ProductoValidationRules $request)
    {   
        $vIntIdProducto = 0;

        try {
            $validated = $request->validated();

            DB::beginTransaction();

            $vIntIdProducto = ProductsModel::insertGetId([
                'f014_nombre' => $request['nombre'],
                'f014_precio_basico'=> $request['vlrBasico'],
                'f014_precio_premium' => $request['vlrPelete'],
                'f014_categoria_id'  => $request['categoria'],            
                'f014_id_coleccion'=> $request['coleccion'],
                'created_at'=> Carbon::now()->toDateTimeString(),     
                'f014_creado_por'=> Auth::id(),
            ]);

            foreach (Arr::get($request,'colores') as $key => $color) {
                ProductoMaterialModel::insert([
                    'f019_producto_id' => $vIntIdProducto,
                    'f019_crosta_id'=> Arr::get($color,'crosta.valor'),
                    'f019_id_folia1' => Arr::get($color,'folia1.valor'),
                    'f019_id_folia2'  => Arr::get($color,'folia2.valor'),          
                    'f019_id_folia3'=> Arr::get($color,'folia3.valor'),
                    'f019_color'=> Arr::get($color,'color'),
                    'f019_creado_por'=> Auth::id(),
                ]);
            }

            DB::commit();

            return response()
            ->json(['status' => true]);

        } catch (\Throwable $th) {
            DB::rollBack();
            return response()
            ->json([
                'status' => false,
                'message' => 'Fallo la creación del producto '.$th->getMessage()
            ]);
        }
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        $vProductsModel = ProductsModel::with(
                            'MaterialesCombinaciones.Crostas',
                            'MaterialesCombinaciones.Folia1',
                            'MaterialesCombinaciones.Folia2',
                            'MaterialesCombinaciones.Folia3'
                        )
                        ->where('f014_id',$id)
                        ->get();

        return response()
                ->json($vProductsModel);
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $vProductos = null;

        try {
            DB::beginTransaction();

            $vProductos = ProductsModel::find($id);
            $vProductos->f014_precio_basico = $request['vlrBasico'];
            $vProductos->f014_precio_premium = $request['vlrPelete'];
            $vProductos->f014_modificado_por = Auth::id();

            $vProductos->save();

            foreach (Arr::get($request,'colores') as $key => $color) {
                ProductoMaterialModel::updateOrCreate(
                    [
                        'f019_producto_id' => $id, 
                        'f019_crosta_id' => Arr::get($color,'crosta.valor'),
                        'f019_color'=>Arr::get($color,'color')
                    ],
                    [
                        'f019_id_folia1' => Arr::get($color,'folia1.valor'),
                        'f019_id_folia2' =>  Arr::get($color,'folia2.valor'),
                        'f019_modificado_por'=>Auth::id()
                    ]
                );
            }


            DB::commit();
            return response()
            ->json(['status' => true]);
        } catch (\Throwable $th) {

            DB::rollBack();
            return response()
            ->json([
                'status' => false,
                'message' => 'Fallo la actualización del producto '.$th->getMessage()
            ]);
        }
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        ProductsModel::destroy($id);
    }
}

我认为这是错误的:

 $vIntIdProducto = ProductsModel::insertGetId([
                'f014_nombre' => $request['nombre'],
                'f014_precio_basico'=> $request['vlrBasico'],
                'f014_precio_premium' => $request['vlrPelete'],
                'f014_categoria_id'  => $request['categoria'],            
                'f014_id_coleccion'=> $request['coleccion'],
                'created_at'=> Carbon::now()->toDateTimeString(),     
                'f014_creado_por'=> Auth::id(),
            ]);

            foreach (Arr::get($request,'colores') as $key => $color) {
                ProductoMaterialModel::insert([
                    'f019_producto_id' => $vIntIdProducto,
                    'f019_crosta_id'=> Arr::get($color,'crosta.valor'),
                    'f019_id_folia1' => Arr::get($color,'folia1.valor'),
                    'f019_id_folia2'  => Arr::get($color,'folia2.valor'),          
                    'f019_id_folia3'=> Arr::get($color,'folia3.valor'),
                    'f019_color'=> Arr::get($color,'color'),
                    'f019_creado_por'=> Auth::id(),
                ]);
            }

0 个答案:

没有答案