简体   繁体   中英

Call function in one controller to another controller

I am new to Laravel. I have some functions in PaymentController . I want to call those functions from SmartpaySController . Here is the function which is available in PaymentController . Help me to call that function by staying in SmartpaySController .

public function getPaymentFailed($paymentId) {

        $transactionData = $this->paymentRepo->find($paymentId);
        if($transactionData) {
            $data['quote'] = $this->quoteRepo->getQuoteById($transactionData->quote_id);
            $data['metaTitle'] = 'Payment failed';
            $data['returnMessage'] = $transactionData->return_message;
            return view('payment::payment.quote_payment_failed', $data);
        }
}

Thank you.

Change:

public function getPaymentFailed($paymentId)

to:

public static function getPaymentFailed($paymentId)

This will make it staticly available in your SmartpaySController by doing:

PaymentController::getPaymentFailed($paymentId);
Instead of calling controller methods, the better practice is that you can create traits like: app/Traits  and extend in controller

//trait

trait traitName {

    public function getData() {
        // .....
    }
}

//Controller

class ControlelrName extends Controller {
     use TraitName;
}

I recomend you to not call functions from one controller to another. Make Helpers, Resources or implement same feature in other way

Never use controllers as object

But if you want to do it anyway you can use:

SomeController.php
 class SomeController extend Controller { public function someFunction(Request $request) { // Here Some Code } }
YourController.php
 use SomeController; ... public function getPaymentFailed(Request $request, $paymentId) { $controller_data = (new SomeController)->someFunction($request); $transactionData = $this->paymentRepo->find($paymentId); if($transactionData) { $data['quote'] = $this->quoteRepo->getQuoteById($transactionData->quote_id); $data['metaTitle'] = 'Payment failed'; $data['returnMessage'] = $transactionData->return_message; return view('payment::payment.quote_payment_failed', $data); } }

You can make use of Real-Time Facades

Using real-time facades, you may treat any class in your application as if it were a facade.

To generate a real-time facade, prefix the namespace of the imported class with Facades:

//...

use use Facades\App\Http\Controllers\SomeController;

//...

return SomeController::getPaymentFailed($request, $paymentId);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM