Passing variable to method from another controller

I am developing a Laravel 8 application, and I need to create XML files with data from the database.
So I first created the controller and method to generate the XML file and tested it to work correctly.
Now I need to call the exportXML method of the ExportFileController inside the PrenotazioneSpedizioneController controller.
Reading the Laravel documentation and here on Stack I saw that you can call the method like this App::call('AppHttpControllers[email protected]');.

I tested it without parameters, and it works as expected.
The problem I have now is the following, is it possible to pass a parameter to the exportXML method which I call with:

App::call('AppHttpControllers[email protected]');?

I was thinking something like App::call('AppHttpControllers[email protected]')->with('racc', $racc);.

I appreciate any suggestions or advice.

  • PrenotazioneSpedizioneController

<?php

namespace AppHttpControllers;

use IlluminateHttpRequest;
use AppModelsCodiciPrenotazione;
use AppModelsRaccomandata;
use AppModelsPrenotazioni;
use IlluminateSupportFacadesAuth;
use IlluminateSupportFacadesDB;
use IlluminateSupportFacadesLog;

class PrenotazioniSpedizioniController extends Controller
{

    // dashboard delle prenotazioni
    public function index()
    {
        $page_title = 'Resoconto prenotazioni';
        $page_description = 'Pagina di resoconto delle prenotazioni effettuate';
        $logo = config('dz.public.logo');
        $logoText = config('dz.public.logo_text');
        $active = "active";
        $action = 'dashboard_4';

        $total = CodiciPrenotazione::count();
        
        $free = CodiciPrenotazione::where('stato', 0)->count();

        $codici = CodiciPrenotazione::select('*')->get()->toArray();

        return view('prenotazioni.dashboard', compact('page_title', 'page_description', 'logo', 'logoText', 'active', 'action'))
        ->with('total', $total)
        ->with('free', $free)
        ->with('codici', $codici);
    }

    // GESTIONE DELLE SPEDIZIONI
    public function gestisciSpedizione(Request $request){
       
        try{

            set_time_limit(-1);

            //devo recuperare le raccomandate dal DB con isGenerated = 0 e per data e lotto

            //prendo la data odierna, devo spedire quelle con data precedente.
            $date = date('Y-m-d');
            //recupero le raccomandate
            $racc = Raccomandata::select('*')
            ->where([
                ['isGenerated', '=', '0'], //non generate
                ['created_at', '>', $date.' 00:00:00'], //la data di creazione deve essere precedente la data odierna
                ['idCliente', '=', '1'], //selezioniamo le raccomandate solo per il cliente
            ])
            ->get();
            //raggruppiamo per idCommessa e cronologico
            $racc = $racc->groupBy(['idCommessa', 'cronologico'])->toArray();
            

            //passo alla creazione dei file
            //richiamo la procedura per generare i file .xml
            return App::call('AppHttpControllers<a href="https://getridbug.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="96d3eee6f9e4e2d0fffaf3d5f9f8e2e4f9fafaf3e4d6f3eee6f9e4e2cedbda">[email protected]</a>'); // here i want pass $racc variable.





            //loggiamo l'evento e redirectiamo con il messaggio di success dell'operazione
            Log::channel('custom_log')->info('L'utente '.Auth::user().' ha prenotato con successo la spedizione numero: '.$request->input('codice_prenotazione').' FILE :');

            return redirect()->back()->with('success', 'Prenotazione della spedizione effettuata con successo');

        }catch(Exception $e){
            Log::channel('custom_log')->info('L'utente '.Auth::user().' non è riuscito a prenotare la spedizione COD:'.$request->input('codice_prenotazione').' ERRORE:'.$e);

            return redirect()->back()->with('error', 'Non è stato possibile prenotare la spedizione numero: '.$request->input('codice_prenotazione'));
        }
    }

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

You should not call controllers inside another controllers.

You are facing this problem because you are putting business logic inside your controllers (and it is a well known bad practice).

The solution is to use another class, called a service class, where you put the logic. You then call this class where you need to (in your case, in PrenotazioniSpedizioniController and ExportFileController).

This is a quick example:

Create the file appServicesExportService.php:

class ExportService {
    public function exportXML($arguments)
    {
        //something
    }
}

Then, in your controllers:

use AppHttpControllersExportFileController;

class PrenotazioniSpedizioniController extends Controller
{
     public function yourMethod(Request $request){
         app(ExportService::class)->exportXML($arguments);
     }
}

This way you keep clean controllers and have a more testable code.

Keep in mind this is a minimal example to solve your problem and I can only advise you to dig further on project architecture and design patterns.

Method 2

You should not call controllers inside another controllers.

You are facing this problem because you are putting business logic inside your controllers (and it is a well known bad practice).

The solution is to use another class, called a service class, where you put the logic. You then call this class where you need to (in your case, in PrenotazioniSpedizioniController and ExportFileController).

This is a quick example:

You should not call controllers inside another controllers.

You are facing this problem because you are putting business logic inside your controllers (and it is a well known bad practice).

The solution is to use another class, called a service class, where you put the logic. You then call this class where you need to (in your case, in PrenotazioniSpedizioniController and ExportFileController).

This is a quick example:

Create the file appServicesExportService.php:

class ExportService {
    public function exportXML($arguments)
    {
        //something
    }
}
Then, in your controllers:

use AppHttpControllersExportFileController;

class PrenotazioniSpedizioniController extends Controller
{
     public function yourMethod(Request $request){
         app(ExportService::class)->exportXML($arguments);
     }
}
This way you keep clean controllers and have a more testable code.

Keep in mind this is a minimal example to solve your problem and I can only advise you to dig further on project architecture and design patterns.

This way you keep clean controllers and have a more testable code.

Keep in mind this is a minimal example to solve your problem and I can only advise you to dig further on project architecture and design patterns.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x