Controller
What is controller

We run Controller by Route. Controller communicate between Views and Models, we can create controller by php artisan or we can create controller directly but Remember that controller file name,name of the class name should be same.

To create controller

1. Open command prompt
2. Goto you folder. Suppose we goto c:/xampp/htdocs/laravel
3. Then enter artisan command
php artisan make:controller UserController

After this command we will a new file(UserController.php) is created in laravel/app/Http/Controllers/

Code of UserController

<?php

namespace AppHttpControllers;

use IlluminateHttpRequest;

class UserController extends Controller
{
//
}

Run Controller

We can't run directly controller, so we need to create route then run controller

Route
Route::get('testurl','UserController@show');

First parameter is testurl is url that we run and second parameter is controller name with function name

Controller
<?php

namespace AppHttpControllers;

use IlluminateHttpRequest;

class UserController extends Controller
{
public  function show(){
echo "This is test Controller";
}
}

Create controller and passing value by url to controller

Route

Route::get('testurl/{id}','UserController@show');

Controller

<?php

namespace AppHttpControllers;

use IlluminateHttpRequest;

class UserController extends Controller
{
public  function show($id){
echo $id;
}
}

Create controller and passing value by url(Numerice Mandatory) to controller

Route

Route::get('testurl/{id}','UserController@show')->where(['id'=>"[0-9]+"]);;

Controller

<?php

namespace AppHttpControllers;

use IlluminateHttpRequest;

class UserController extends Controller
{
public  function show($id){
echo $id;
}
}

In this example passing argument must be numeric between 0-9 like
testurl/45 is correct
testurl/ravi is wrong because ravi is character not numeric


Previous
Next