Showing posts with label Laravel Service. Show all posts
Showing posts with label Laravel Service. Show all posts

Monday, July 3, 2017

Laravel 5: Get Service Instance In Controller Dynamically | Get Service Instance In Service Dynamically

The Laravel service container is a powerful tool for managing class dependencies. Dependency injection is a fancy word that essentially means this: class dependencies are "injected" into the class via the constructor.

There are several ways to resolve something out of the container. First, you may use the make method as below example:

$service = app()->make("App\\Service\\EmployeeService");

So it makes life easier.

Friday, June 16, 2017

Laravel 5.X: Access HTTP Request From Controller | Service

It's very important to access HTTP Request from Laravel Controller or Service. Below is a code example showing how to access HTTP Request from Laravel Controller. Same for Service.


<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request as HttpRequest;
use Illuminate\Routing\Controller as BaseController;

class HomeController extends BaseController
{
    private $HttpRequest;
    public function __construct(HttpRequest $HttpRequest)
    {
        $this->HttpRequest = $HttpRequest;
    }

    public function checkHttpRequest() {
        echo $this->HttpRequest->get("id") . "<BR>";
        echo $this->HttpRequest->getBaseUrl() . "<BR>";
        echo $this->HttpRequest->getUri();
        die();
    }
}









Saturday, February 25, 2017

A simple guide to using Traits in Laravel 5

Its great if we can use trait in our application. Laravel has the ability to give us that freedom to use trait. Laravel is a strong php based framework today. At first we have to create a trait, but its nothing but a php class except we use here a keyword named 'trait' & surely this class has no constructor as it cannot be instantiated. So lets start with use of trait.

First we have to create a php file named "TestTrait.php" as follows:

namespace App\Trait;

trait TestTrait {
    public function someFunction() {
        
    }
}

I think you have already have good knowledge about namespace described in Laravel.

Now we have to use this trait in some Controller or Service etc...

Lets see an example of use of trait in Controller.

First we have to import "TestTrait" in our Controller as follows:

//First step is import
use App\Trait\TestTrait;
class TalentMapperController extends Controller
{
    //Second step is tell our Controller to use trait
    use TestTrait;
    
    public function __construct() {
        //Third & final step is apply functions from here
        super::someFunction();
    }
}