
Laravel API response format
You can create a common response format for API response using a function in laravel. You can call this function to return the data or errors as an API response on call a route in laravel.
Answers 1
-
Function to create laravel API response format
function create_output($is_success = false, $error=[], $data=[]) { if( $is_success ) { $output = ['success' => 1]; if(count($data) > 0) { $output['data'] = $data; } } else { $output = [ 'success' => 0, 'errors' => $error ]; } return $this->array_filter_recursive($output); } function array_filter_recursive($array, $callback = null) { return $array; foreach ($array as $key => & $value) { if (is_array($value)) { $value = $this->array_filter_recursive($value, $callback); } else { if ( ! is_null($callback)) { if ( ! $callback($value)) { $array[$key] = ''; } } else { if ( ! (bool) $value) { $array[$key] = ''; } } } } unset($value); return $array; } //Call function and return data as API response //Return the status success with data return $this->create_output(1, [], [ 'id' => $user->id ]); // Return success with no data return $this->create_output(1); //Return status (success) false with validation error message return $this->create_output(0, $validator->errors()->all());
0You can create a trait and copy/paste function in the trait file and call the function in from the controller’s method after importing the trait in the controller file.
Random Code Snippet Queries: Laravel
- Attempt to read property "avatar" on null in Laravel
- There are no commands defined in the "route:" namespace
- Send post data from controller to view
- How to create new user without form submission in laravel
- How to update record after save method in Laravel
- Add [name] to fillable property to allow mass assignment on [App\Models\Project]
- How to create and run user seeder in laravel
- How to start websocket server in laravel
- Validation for multiple forms on same page in laravel
- Property [user] does not exist on this collection instance
- Root composer.json requires php ^7.3 but your php version (8.0.0) does not satisfy that requirement
- How to pass two variables in HREF in laravel
- Generate unique username in Laravel
- Class "App\Http\Controllers\Auth\Verified" not found
- Remove several global scope from query
- Display success message in laravel
- How to get path from current URL in Laravel
- Delete records with relationship in laravel
- After image selected get validation error in laravel
- Get id of last inserted record in laravel
- How to create laravel project using composer
- How to pass query string with pagination in laravel
- Input file with max size validation in laravel
- Use of undefined constant laravel
- The Pusher library requires the PHP cURL module. Please ensure it is installed