mercredi 16 décembre 2015

Laravel API connecting to multiple databases

I'm building a REST API with Laravel (Lumen). The idea is that this API provides the back-end for multiple food-ordering websites. They share the same back-end logic (models, controllers etc.). This way each website only needs it's own front-end application, I'm planning to use Angular for this. Each website will have it's own data (products, pages etc.), which has to be stored in different databases.

I've defined multiple connections within config/databases.php for testing purposes. Now I can dynamically set the connection before querying the corresponding database, like this:

class ProductController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return Response
     */
    public function index()
    {   
        $products = new Product;
        $products->setConnection('customer_two'); // <--
        $products = $products->get();

        return response()->json($products);
    }
}

The same can be done with caching, for instance.

What's the best way to let the API know which customer's website made the request? I need to point to the right database. Also, could this approach cause any problems performance-wise?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire