Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel method that can be used by multiple controllers and commands. Where should it be?

I'd like to define a "global" method that can be used by multiple controllers and commands. Where should it be placed in Laravel 5.4?

Let's say I have the following controller. How would I call the "global" method instead, and where would that "global" method be located exactly?

<?php

namespace App\Http\Controllers;
use Illuminate\Http\Request;

use App\Flight;

class FlightsController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Index
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $flights = Flight::where('active', 1)
               ->orderBy('name', 'desc')
               ->take(10)
               ->get();

        foreach ($flights as $flight) {
            if ( $flight->price == 0 )
            {
                $output = "some value";
            }
            else
            {
                $output = "some other value";
            }
        }

        return view('flights.index')
                ->with(['output'   => $output])
                ;
    }
}
like image 487
user3489502 Avatar asked Oct 26 '17 13:10

user3489502


People also ask

Where is Laravel controller can be located?

In Laravel, a controller is in the 'app/Http/Controllers' directory. All the controllers, that are to be created, should be in this directory. We can create a controller using 'make:controller' Artisan command.

Which of the following commands is used to create controller?

Step 1 − Create a controller called MyController by executing the following command. app/Http/Controllers/MyController. php file.

Where is the routing file located in Laravel?

All Laravel routes are defined in your route files, which are located in the routes directory. These files are automatically loaded by your application's App\Providers\RouteServiceProvider . The routes/web.


1 Answers

When you want a method that fetches many models, and you want to use it in many places, put it in a Repository:

class FlightRepository
{
    public function getLastTenFlights()
    {
        return Flight::where('active', 1)
           ->orderBy('name', 'desc')
           ->take(10)
           ->get();
    }
}

For example from your controller:

public function index( FlightRepository $repo )
{
    $flights = $repo->getLastTenFlights();

    //if you want you can put this additional login in the method too... 
    foreach ($flights as $flight) {
        if ( $flight->price == 0 )
        {
            $output = "some value";
        }
        else
        {
            $output = "some other value";
        }
    }

    return view('flights.index')
            ->with(['output'   => $output])
            ;
}
like image 172
Moppo Avatar answered Oct 10 '22 11:10

Moppo