Showing posts with label Laravel HTTP Request. Show all posts
Showing posts with label Laravel HTTP Request. Show all posts

Sunday, June 18, 2017

Laravel 5.X Forward To URL | Redirect To Route | Forward Request | Mock Request | Mock HTTP Request | Dynamic HTTP Request | Laravel Dispatch Request

Laravel 5.X Forward To URL | Redirect To Route | Forward Request | Mock Request | Mock HTTP Request | Dynamic HTTP Request.

It's easy to forward a request using Laravel Route. Forwarding do for you is URL will not change but response will change. The way it is working is that it will mock a request using Request::create(...) and dispatch using current Router.

<?php
namespace App\Http\Controllers;

use Illuminate\Routing\Router;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request as HttpRequest;

class MyController extends Controller {
    public function __construct(HttpRequest $httpRequest, Router $router) {
        $this->middleware('auth', ['except' => ['action1', 'action2']]);

        $this->httpRequest = $httpRequest;
        $this->appRouter = $router;
    }

    //Route=my/need-forward (Create new request and dispatch)
    public function needForward() {
        //http://www.domain.com/my/need-forward
        $route_name = action("MyController@forwardHere");
        //http://www.domain.com/other-folder/my/need-forward
        $route_name = action("OtherFolder\\MyController@forwardHere");
        //http://www.domain.com/my/need-forward/100/Name%20Text?roll=303
        $route_name = action("MyController@forwardHere", ["id" => 100, "name" => "Name Text", "roll" => 303]);
        $request = HttpRequest::create($route_name, 'GET', array("param1" => "Param 1", "param2" => "Param 2"));
        return app()->handle($request);
    }

    //Route=my/need-forward (Forward same request to new route)
    public function needForward2() {
        $route_name = "my/forward-here";
        $request = HttpRequest::create($route_name);
        return  $this->appRouter->dispatch($request);
    }

    //Route=my/forward-here
    public function forwardHere() {
        echo "Browse [/my/need-forward] will send output of [/my/forward-here]";
    }
}


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();
    }
}