Reputation: 501
I want to reuse my method store
that is in generar\productoController
public function store(Request $request){}
and I want to reuse it in this class adquisicion\ComprasController
, I know that I have to import the class to use the method i want, but the problem is the $request variable, should I create a new object of it with $request = new Request()
, adding the data I want with this and sending it as parameter?
Thx for the help I'm really new with laravel
Upvotes: 0
Views: 1472
Reputation: 5129
Here are two ways that can make methods reusable in laravel application:
Make a helper method
Create a Helpers
folder in app
folder, and create all static methods inside a helper.php
Helper.php
namespace App\Helpers;
class Helper {
public static function store() {
$request = request();
// ....
}
}
YourController.php
namespace App\Repositories;
use App\Helpers\Helper;
use Illuminate\Http\Request;
class YourController extends Controller
{
public function store(Request $request) {
// call the store method as
Helper::store();
}
}
The downside here is you will mix up all the non-related helper methods here and may difficult to organize.
Repository
You can use a Repository Pattern to architect your application, for example, if you store a foo
object to your datastore, then you can first create Repositories
folder in app
folder, and create FooRepository.php
in Repositories
folder:
FooRepository.php
namespace App\Repositories;
class FooRepository {
public function store() {
$request = request();
// ...
}
}
YourController.php
namespace App\Http\Controllers;
use App\Repositories\FooRepository;
use Illuminate\Http\Request;
class YourController extends Controller
{
private $fooRepository = null;
public function __construct(FooRepository $fooRepository) {
parent::__construct();
$this->fooRepository = $fooRepository;
}
public function store(Request $request) {
// call the method as
$this->fooRepository->store();
}
}
Upvotes: -1
Reputation: 970
You can pass Request
data to other method
productoController(Request $request){
// anything here
return redirect('your route name')->with('data', $request->all());
}
Upvotes: 0
Reputation: 838
you can try it like this $this->store(request(),$otherData)
use the helper to get the current object of request
Upvotes: 1