The HTTP status code "0" is not valid.
public function filter()
{
$institute = (new Institute)->newQuery();
$institute->with(['locations','courses' => function ($query) use ($request){
$query->with('trainers');
}]);
}
$data = $institute->get();
if(count($data) > 0)
{
return response()->json($data);
}
else
{
return response()->json(404,'No Data found');
}
}
Actually, I want to display error 404 message if there is no data,
my problem is when I try to check whether data is there or not I'm getting an error called InvalidArgumentException.Can anyone help on this please.
return response()->json(404,'No Data found');
The first argument of json should be data, then goes a status code. In this case the status code gets 0 value. Simply do it as follows:
return response()->json('No Data found', 404);
This error is thrown when you try and use 0 as your response exception code. In my case my App/Exceptions/Handler.php file was modified and I returned 0 as my HTTP code after formatting which is not allowed. Just make sure you are returning a valid HTTP code from your Exception handler at all times.
Another case can cause the same problem when you have a difference between code and database schema.
In laravel, I had this issue when trying to do an insert on a table where I had the field type incorrect. In my specific case, I was trying to insert a varchar into an integer field in my DB Schema.
Changed the Schema to varchar and I was all set!
Related
I am working on a module and want to throw an error message of 401 when the value is false.
I am doing something like this.
if(!$data) {
throw new \ErrorException('Error found');
}
any better way to do this?
You could use one of the helper methods to throw exceptions and display error messages as a response. See here: https://laravel.com/docs/master/helpers#method-abort
The same result could be achieved with abort_unless().
// If data evaluates to false.
abort_unless($data, 401, 'Error found');
I'm not sure how they work, I was thinking that accessor fires when you access the attribute, however when I try to insert new record my accessor fires. I store in my database only image_name by removing URL and I use an accessor to include my URL route when I retrieve my image name. I found out that my accessor fires on insert and change my input:
ImageRepository.php
public function save($imageData)
{
$this->model->owner()->associate(auth()->user());
$this->model->type = $imageData->type;
$this->model->image_name = $imageData->image_url;
$this->model->save();
return $this->model;
}
Image.php
public function getImageNameAttribute($value)
{
$filePath = 'my_path';
// check if method was hit
logger()->info('getImageNameAttribute: '.$value);
// return default image if not found
if ($value == '' || $value == null || Str::contains($value, 'no-image.png') || !File::exists(public_path($filePath))) {
return asset('img/no-image.png');
} else {
return asset($filePath);
}
}
Input for $imageData->image_url:
https://some-random-image-url/image-name.jpg
Inserted data:
img/no-image.png
Excepted output (I have a function that extracts the name from URL):
image-name.jpg
When I check the log, I get the message:
getImageNameAttribute: https://some-random-image-url/image-name.jpg
Can someone explain to me if I'm doing something wrong or this is working as pretended?
I did solve the problem, I miss checked. Actually inserted record in my database is correct:
image-name.jpg
But I was checking dd() output after the insert and the value from there was not correct:
img/no-image.png
Because when dd() fires, the accessor is also fired (as we are retrieving data) and as the image was not downloaded it was actually showing correct data.
I have this code :
$status = htransaksi::find(auth()->user()->id)->where('Status','Open')->count();
if ($status != 0)
{
$idhtrans = htransaksi::select('id')->where('User_ID', auth()->user()->id)->where('Status', 'Open')->first();
$shopcart = DB::table('detiltransaksis')->join('Barangs', 'Barangs.id', '=', 'detiltransaksis.barang_Id')->where('htrans_Id', $idhtrans->id)->get();
return view('home')->with('barang', $barang)->with('jenis', $jenis)->with('shopcount',$shopcart);
}
else
{
return view('home')->with('barang', $barang)->with('jenis', $jenis);
}
This code checks, is there any item in your shopping cart? If there is an item then return that shopping cart and when there is no item it shows some error that say
Call to a member function where() on null
Anyone knows how to fix this?
I'm new to Laravel and sorry if this is such a newbie question.
Edit :
The error point to
$status = htransaksi::find(auth()->user()->id)->where('Status', 'Open')->count();
The issue is in this line:
$status = htransaksi::find(auth()->user()->id)->where('Status','Open')->count();
if htransaksi::find(auth()->user()->id) returns null then your code will call where on null hence the error:
Call to a member function where() on null
You can simply add a condition and do it separate:
$entryFound = htransaksi::find(auth()->user()->id);
if (empty($entryFound)) {
//this means its returning null then handle that condition here
}
//if entry is found then leave the code as is:
$status = $entryFound->where('Status','Open')->count();
if(Auth::check()) {
$status = htransaksi::where('user_id', Auth::id())->where('Status','Open')->count();
... your "normal logic"
} else {
$error_handling_user_not_logged_in();
}
The reason why I added the Auth::check() check is to make sure that the user is really logged in, feed free to remove it if you already know this because of middleware/request validation.
You code did not work because htransaksi::find(auth()->user()->id) returns a finished data set - if this dataset is empty PHP's where() function failed because you tried to search something which is NULL
As I see htransaksi::find(auth()->user()->id)->where('Status','Open')->count(); is incorrect. You cannot use where() function after find().
Let's try:
$status = htransaksi::where('User_ID',auth()->user()->id)->where('Status','Open')->count();
When i search by city name which is available in my database table it will show the result but when i search by unknown city which is not available in my database table it says -No query results for model [App\City]. i am sharing you the code and screenshot see error screenshot
actually i want to redirect to 401 page if the city is not found in my database table
Here is my route
Route::get('teacher-jobs-by-city/{city}','TeacherJobsController#by_location');
Here is my function
public function by_location($location_id='')
{
$data= array();
$location = City::where('slug',$location_id)->where('status','1')->firstOrFail();
$items= Subject::orderBy('id','asc')->get();
$data['location']=$location;
//$subjects = [''=>'Select Subject'] + Subject::lists('subject_title','id')->toArray();
//$city = [''=>'Select City'] + City::lists('name','id')->toArray();
$active_class ='Select Subject to see job Openings';
return view('frontend.teacherjobs.by_location',compact('active_class','data','items'));
}
That's because you are using the firstOrFail() method, that as named, fails if theres no result by throwing an Exception that will be redered as "No query results for model ..." message.
If you want to it don't fail, you can:
Surround your query with a try-catch block, handling the exception and return some message
Replace the firstOrFail() method by first()
You can handle that kind of error by modifying the way Illuminate\Database\Eloquent\ModelNotFoundException Exception are handle. In the App\Exceptions\Handler class change the render method to look like this
public function render($request, Exception $exception)
{
if($exception instanceof ModelNotFoundException){
return redirect("/error_page", 401)->with('error', $e->getMessage());
}
return parent::render($request, $exception);
}
Within the redirect your must put the route to which you want to be redirected, I put /error_page just for sample purpose.
You can learn more on Error Handling'
Don't forget to import the ModelNotFoundException like this use Illuminate\Database\Eloquent\ModelNotFoundException;
Adding on to the answer by Elias Soares, This happens because laravel generates an "Illuminate\Database\Eloquent\ModelNotFoundException" exception if firstOrFail don't return results.
Reference: https://laravel.com/docs/5.8/eloquent#retrieving-single-models
It's upto you how you want to handle this exception. If using firstOrFail -> to first() solution
After replacing firstOrFail with first, You would get the error: "Trying to get property of non object", That's because your query didn't fetched anything, so it won't have attribute. For that you can place a check on the results of your query.
$location = City::where('slug',$location_id)->where('status','1')->first();
!empty($location->attribute)?$location->attribute:null;
Replace this:
$location = City::where('slug',$location_id)->where('status','1')->firstOrFail();
With this:
$location = City::where('slug',$location_id)->where('status','1')->first();
the following function is supposed to read the name of the given asset code from the database. but it triggers the error: "Trying to get property of non-object"
function sban_name($asset){
$this->db->select('name');
$this->db->from('asset_types');
$this->db->where('code',$asset);
return $this->db->get()->result()->row('name');
}
All I want is to have the name of the asset returned back to the controller! Your help is highly appreciated!
Use row() like,
return $this->db->get()->row()->name;
Use row() for a single row, and result() for multiple rows.
do like this, asset_types is your table name
function sban_name($asset){
$this->db->select('name');
$this->db->from('asset_types');
$this->db->where('code',$asset);
return $this->db->get('asset_types');
}
And in your controller acess it like
$result=$this->modelname->sban_name('$asset')->row();
$name=$result->name;
I think it's important to check if the record that satisfies the conditions even exists in the database. Code for the model:
function sban_name($asset){
$this->db->select('name');
$this->db->from('asset_types');
$this->db->where('code',$asset);
$row = $this->db->get()->row();
if (isset($row)) {
return $row->name;
} else {
return false;
}
}
Simply call the function from the controller like so:
$response = $this->model_name->sban_name($asset)
Try this code of block , I already checked and works fine:
function sban_name($asset)
{
$this->db->select('name');
$this->db->from('asset_types');
$this->db->where('code', $asset);
return $this->db->get()->row()->name;
}