Capitulo 12 del Módulo 2 API Rest | BackEnd

➜ CRUD Empresa

Métodos CRUD para el modelo Empresa | Implementación de los métodos CRUD index, store, show, update y destroy para el modelo Empresa en el EmpresaController

Empresas

Api/Admin/EmpresaController

<?php

namespace App\Http\Controllers\Api\Admin;

use App\Models\Empresa;
use Illuminate\Support\Str;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class EmpresaController extends Controller
{
    public function index(){
        $data = Empresa::orderBy("orden")->get(["id","nombre"]);
        return response()->json($data, 200);
    }

    public function store(Request $request){
        // validación
        $data = new Empresa($request->all());
        /// upload image base64
        if($request->urlfoto){
            $img = $request->urlfoto;
            /// process
            $folderPath = "/img/empresa/";
            $image_parts = explode(";base64,", $img);
            $image_type_aux = explode("image/", $image_parts[0]);
            $image_type = $image_type_aux[1];
            $image_base64 = base64_decode($image_parts[1]);            
            $file = $folderPath . Str::slug($request->nombre) . '.'.$image_type;
            file_put_contents(public_path($file), $image_base64);
            $data->urlfoto  =   Str::slug($request->nombre) . '.'.$image_type;
        }              
        $data->save();
        return response()->json($data, 200);
    }

    public function show($id){
        $data = Empresa::find($id);
        return response()->json($data, 200);
    }

    public function update(Request $request, $id){
        // validación ...
        $data = Empresa::find($id);
        $data->fill($request->all());
        if ($request->file){            
            $img = $request->file;
            $folderPath = "/img/categoria/"; //path location            
            $image_parts = explode(";base64,", $img);
            $image_type_aux = explode("image/", $image_parts[0]);
            $image_type = $image_type_aux[1];
            $image_base64 = base64_decode($image_parts[1]);
            
            $file = $folderPath . Str::slug($request->nombre) . '.'.$image_type;
            file_put_contents(public_path($file), $image_base64);
            $data->urlfoto  =   Str::slug($request->nombre) . '.'.$image_type;
        }             
        $data->save();        
        return response()->json($data, 200);
    }

    public function destroy($id){
        $data = Empresa::find($id);
        $data->delete();
        return response()->json("Borrado", 200);
    }
}

 


1164 visitas

Capítulo 13 – Rutas y Layouts »

Descarga el código del proyecto

Descarga el código fuente del proyecto adquiriendo el curso completo

Comprar

¡Qué aprenderás?

tooltip bs-tooltip-top bs-tooltip-end bs-tooltip-bottom bs-tooltip-start show fade tooltip-inner

Codea Applications

México, Colombia, España, Venezuela, Argentina, Bolivia, Perú