Reputation: 1453
Suppose I have a search form which submit the search parameters to a post method with ajax, on that method I have returned the result in a view. Now on that view I have an option for user to select the range of record for printing in excel, so for this once again I need to submit the search parameters along with print settings to one another post method, on that method I need to search again for search parameters, and also limit the search for selected print ranges. So for this I need the same code block, but for avoiding that is it possible to call the search post method from within the print post method? If possible How can I do that? Or any other way?
Upvotes: 2
Views: 2681
Reputation: 6202
First of all, if you are passing some data from client to server using POST, it will be available in every method. You don't have to pass it from one to another.
In your case, it is better to move your business logic to a repository. You can create a new folder called repositories
, under app
directory. Then create a new repository class say SearchRepository
, something like below
namespace App\Repositories;
use Illuminate\Http\Request;
class SearchRepository {
public function __construct(Request $request) {
$this->request = $request;
}
/**
* Search details
*
* @return array
*/
public function getDetails() {
$q = $this->request->get('q');
$limit = $this->request->get('limit');
// Do the search operation with parameters recieved
return $result;
}
}
You can use the above repository in any controller using dependency injection like below. This way, you don't need to repeat any of your business logic with in controller.
namespace App\Http\Controllers;
use App\Repositories\SearchRepository
class SearchController extends Controller {
public function __construct(SearchRepository $search) {
$this->search = $search;
}
public function searchAction() {
$result = $this->search->getDetails();
// return to view or whatever
}
public function printAction() {
$result = $this->search->getDetails();
// print excel code or whatever
}
}
Upvotes: 3