Showing posts with label controller. Show all posts
Showing posts with label controller. Show all posts

Tuesday, July 11, 2017

Laravel 5: Get Controller Name in View | Route Details | Controller & Action Name | Route Parameters

You can create a view composer that injects those variables into your view file. In "app/Providers/AppServiceProvider.php" add something like this:

public function boot()
{
    //app('view')->composer("folder.specific_view_name", function ($view) {
    app('view')->composer("*", function ($view) {
        $action = app("request")->route()->getAction();

        $controller = class_basename($action["controller"]);

        list($controller_name, $action_name) = explode("@", $controller);

        $view->with(compact("controller_name", "action_name"));
    });
}

You also can parameters from current request as below:

app('request')->route()->parameters()

Array
(
    [middleware] => web
    [as] => folder.view_name
    [uses] => App\Http\Controllers\UserController@show
    [controller] => App\Http\Controllers\UserController@show
    [namespace] => App\Http\Controllers
    [prefix] => 
    [where] => Array
        (
        )


)


Sunday, June 25, 2017

Laravel 5: Generate a URL to a controller action

It's easy to generate a URL as like Controller Action. Suppose you have a controller named "UserController" and have an action inside the Controller named "customerLogin" and in routes.php you mentioned the router as: 

"Route::get("login_customer", "UserController@customerLogin"

So when you browse www.domain.com/login_customer then actually executed "customerLogin" action of "UserController".

Now for some reason you need to construct a URL based on Controller and Action, then you can apply below to generate URL:

action('UserController@customerLogin', ['id' => "3 0"])

Will generate below URL:

www.domain.com/login_customer?id=3+0

If you Controller exists inside another folder then you ca

action('Folder\UserController@customerLogin', ['id' => "3 0"])


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









Thursday, May 18, 2017

AngularJS How to call controller function from outside of controller component

Its not a good practice to call AngularJS function from outside of its scope. But sometimes we need it badly. So there is a way around to do this easily.

You should note that scopes are initialized after the page is fully loaded, so calling methods from outside of scope should always be done after the page is loaded. Else you will not get to the scope at all. Below is a small code snippet to how you can achieve this easily:

var targetID = document.getElementById("AngularController");
angular.element(targetID).scope().init("Outside Controller");

Where "init" is function named in your controller as below:

var app = angular.module("myApp", []);
app.controller("AngularController", function($scope, $window) {
    $scope.init = function(res) {
        console.log("INIT INVOKED=" + res);
    };

    $scope.init("Controller Itself");
});








You can download full example from the link.


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

Thursday, November 3, 2016

Create new controller & view in laravel

Open command prompt & navigate to "C:/xampp/htdocs/laravel" (laravel is your laravel project directory) and run following command:

php artisan make:controller TestController

This command will make a controller under directory "app/Http/Controllers"

Now add the following lines to "app/Http/routes.php":
Route::resource('test', 'TestController');

Now create a file named "test.blade.php" under "resources/views" directory with following contents:
Resources/views/test.blade.php<br/>
Name found from params=<?php echo $name; ?>

Your Controller class look like following:


<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use View;
use App\Http\Requests;
use App\Http\Controllers\Controller;

class TestController extends Controller
{
    public function index()
    {
        $data = array();
        $data["name"] = "Pritom Kumar";
        return View::make('test', $data);
    }

    public function create()
    {
        
    }

    public function store(Request $request)
    {
        
    }

    public function show($id)
    {
        
    }

    public function edit($id)
    {
        
    }

    public function update(Request $request, $id)
    {
        
    }

    public function destroy($id)
    {
        
    }
}

?>

Now you can view output by browsing following url: {LARAVEL_ROOT_URL}"/test" 

Monday, September 16, 2013

Grails Controller allow Declarative Exception Handling with Filters

I guess you can handle declarative exception from Controllers but Filters. You can use response instead to send the error code
class AuthorizationFilters {
    def filters = {
        auth(controller: '*' /* or controller name */
            action: '*' /* or action name */, invert: true) {
            before = {
                HashMap map = new HashMap();
                map.put("success", false);
                map.put("message", "Error occurred"); 
                if(1){ //If auth fails
                    response.sendError(5000) /* Custom error code */
                    response.errorMessage = "Error message to error controller";
 
                    // OR 
                    //render(status: 403);
                    //render(contentType: "text/json", text: map.toJSON());
 
                    // OR 
                    //redirect(controller: 'error', action: 'errorDisplay');
                }
                return false
            }
        }
    }
}
Above logic will render the response from ErrorController's errorDisplay action based on the UrlMapping that is provided below.
Make sure you are excluding error controller from filters.

Make sure you have the entry in UrlMappings.groovy:
"5000"(controller: "error", action: "errorDisplay")

And ErrorController.groovy:
class ErrorController {
    def errorDisplay() {
        render(status: 500); /* Change error code to 500 from custom code: 5000 */
        render("Error: "+response.errorMessage);
        //response.errorMessage would be "Error message to error controller";
        return;
    }
}

Monday, July 1, 2013

Cakephp get view file content to a variable from controller

use Cake\View\View;

$html = ''; 
$this->autoRender = false; 
ob_start(); 

$view = new View($this->request);
# OR BELOW
$view = new View($this); 

$view->layout = null; 

/* controller name, a folder exists in views folder */ 
$view->viewPath = "FolderName"; 

/* variable send to view file */ 
$view->set("var", $var); 

$html .= $view->render("file_name"); 
/* a file exists in Views/FolderName/ folder/file_name.ctp */ 

ob_end_clean();

Monday, April 22, 2013