Home » vue » HOW TO SHOW ERROR MESSAGE? LARAVEL AND VUEJS

HOW TO SHOW ERROR MESSAGE? LARAVEL AND VUEJS

Posted by: admin November 26, 2021 Leave a comment

Questions:

I need to know the way to send the error by the controller or know if there is another option to display the error.

VehicleYearController.php

public function store(Request $request)
{
    $this->validate(
        $request,
        [
            'v_year' => 'required|max:4|min:4'
        ],
        [
            'v_year.required' => 'El campo año de inicio es obligatorio',
            'v_year.min' => 'El campo año de inicio debe tener al menos 4 caracteres',
            'v_year.max' => 'El campo año de inicio debe tener a lo más 4 caracteres'
        ]
    );

    $years = DB::table('vehicle_years')->where([
        ['v_id', '=', $request->v_id],
        ['v_year', '=', $request->v_year]
    ])->get();

    if (! $years->isEmpty()) {
        //HERE I NEED TO SHOW THE ERROR THAT THIS DATA ALREADY EXISTS
    } else {
        $data = $request->all();
        VehicleYear::create($data);
    }
}
Answers:

One way would be to add a unique Rule Validation

use Illuminate\Validation\Rule;

$this->validate(
    $request,
    [
        'v_year' => 'required|max:4|min:4',
        'v_id' => Rule::unique('vehicle_years')->where(function ($query) use ($request) {
            return $query->where('v_year', $request->v_year);
        }),
    ],
    [
        'v_id.unique' => 'Your Message',
        'v_year.required' => 'El campo año de inicio es obligatorio',
        'v_year.min' => 'El campo año de inicio debe tener al menos 4 caracteres',
        'v_year.max' => 'El campo año de inicio debe tener a lo más 4 caracteres'
    ]
);

Another way would be to explicitly send out a json response

if (! $years->isEmpty()) {
    return response()->json([
        'errors' => [
            'v_id' => 'Your Message'
        ]
    ], 429);
}

###

public function store(Request $request)
{
    $this->validate($request, [
        'v_year' => 'required|min:4|max:4'
    ], [
        'v_year.required' => 'El campo año de inicio es obligatorio',
        'v_year.min' => 'El campo año de inicio debe tener al menos 4 caracteres',
        'v_year.max' => 'El campo año de inicio debe tener a lo más 4 caracteres'
    ]);
    


    $years = DB::table('vehicle_years')->where([
        ['v_id', '=', $request->v_id],
        ['v_year', '=', $request->v_year]
    ])
    ->get();

    if (!$years->isEmpty()) {
        
         //HERE I NEED TO SHOW THE ERROR THAT THIS DATA ALREADY EXISTS
        //return a json response for consumption in Vue frontend
        return response()->json(['message' => 'This data already exists'], 409);

    }else{
        $data = $request->all();
        VehicleYear::create($data);
    }
}