Published on: 07/8/20 5:36 PM
Category:Code Laravel PHP Tags: Code, GET, Laravel, PHP, POST, ResponsesCreate Helper function
Create new folder in app/http/
by name Helpers
Create new file ResponseBuilder.php
Create new class in ReponseBuilder.php
with function with same name as file, so class name will be ResponseBuilder
first we need to add namespace, as our file is in app\http\Helpers folder, namespace for the file would be namespace App\Http\Helpers;
<?php namespace App\Http\Helpers; class ResponseBuilder { public static function Result($status="", $information="", $data="") { return [ "success"=>$status, "information"=>$information, "data"=>$data ]; } } ?>
Note: here we have created static function, so later we can directly use it without initialization of object using ::
operator.
Call Helper function in GET method
public function GetAllPost() { //return Post::all(); $data = Post::all(); $status = true; $information= "Data is fetched successfully"; return ResponseBuilder::Result($status, $information, $data) }
Call Helper function in POST Method
public function AddPost(Request $request) { $post = new Post; $post->id = $request->input('id'); $post->title = $request->input('title'); $post->content = $request ->input('content'); //$post->save(); $result = $post->save(); if($result == 1) { $status = true; $information = "Data added successfully"; } else { $status = false; $information ="Data not added successfully"; } return ResponseBuilder::Result($status, $information); }
Create Routes
//add post $router->post('/addpost', 'PostController@AddPost'); //get all posts $router->get('/getallpost','PostController@GetAllPost');