lundi 9 novembre 2015

Laravel returns an empty array instead of exception with status 200

I have a problem that when I query a database and get zero results, I get an empty array, though I want to throw a 'ModelNotFoundException'. Here is my sample code:

<?php
#App\Http\Controller\MainController
namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Database\Eloquent\ModelNotFoundException;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Demo;
use DB;


class MainController extends Controller
{

  public function getTagRecords($tag, $limit)
  {
    try{
        $results = Demo::getRecordsByTag($tag, $limit);
    }catch (Illuminate\Database\Eloquent\ModelNotFoundException $e){
        return response()->json(['message'=>'hello there error'], 404);
    }
    return $results;
  }

I am sending a request via AJAX and want to return an error message and status. I have not modified the Handler class.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire