KodeInfo | Learning resources for web and mobile development

Requests & Inputs in Laravel

December 9th, 2014 15:13:47 by Imran Iqbal Comments(0) - Views(11760)

In any web application data and it's manipulation is important. Data doesn't always to be a long term thing. The data provided from an HTML form, or attached to a request is, by default, only available for the duration of the request. Before we can work on data from the request, we will first need to retrieve it.Let's see how we can work on data in Laravel framework. 

Retrieval 

Let's see how we can retrieve some GET data from our URI. This type of data is appended to the URL in the form of key/value pairs.

// app/routes.php

Route::get('/', function()
{
    $data = Input::all();
    var_dump($data);
});

The Input::all() method is used to return an array of both $_POST and $_GET data contained within the request. To get data from $_POST,  we need to create another route to a simple form. 

Note : In Laravel 5 Html and Form classes are not embedded anymore . It is a separate package , so here we didn't used Form class . We will write a separate post to explain Form class in detail .

// app/views/form.blade.php

<form action="{{ url('/') }}" method="post">

   <input name="category" type="hidden" value="technology" /> 
   <input name="blog" type="hidden" value="1234" /> 

   <input type="submit" value="Send" />

</form>

We have created a form, now we have to work on route for this URI before testing. Let's take a look at routing file.

// app/routes.php

Route::post('/', function()
{
    $data = Input::all();
    var_dump($data);
});

Route::get('post-form', function()
{

   return View::make('form');

}

Now if you carefully observe we changed the first route from GET to POST. So this route won't work for GET data, so to handle GET  data. We need to change the form little bit. 

// app/views/form.blade.php

<form action="{{ url('/') }}?category=laravel" method="post">
  
  <input name="category" type="hidden" value="angularjs" /> 
  <input name="blog" type="hidden" value="1234" /> 
  
  <input type="submit" value="Send" />

</form>

But i have a question here when you send POST request which data will come as request data when we retrieve. Check yourself by creating these in your sample application. But GET data takes higher priority than POST data within the request.

Let's see how we can retrieve only the parameter which we needed out of the request data instead of the whole data. To extract single piece of data we have to use Input::get() method.

// app/routes.php

Route::get('/', function()
{

    $data = Input::get('category');
    var_dump($data);

});

If there was no data laravel doesn't throw any exception, instead of that it gives null value. At the same time laravel provides an option to keep a default value for the requested input parameter in the route like below.

// app/routes.php

Route::get('/', function()
{

    $data = Input::get('category','php');
    var_dump($data);

});

Laravel also has a method to check whether the request key parameter was exist or not. If it exists it returns a true otherwise, it will return false value.

// app/routes.php

Route::get('/', function()
{

    $data = Input::has('category');
    var_dump($data);

});

Laravel also has a method called Only() to access only a subset of data out of the request data and also another method which will return only values other than you request called except().

// app/routes.php

Route::get('/', function()
{

    $data = Input::only('category','blog');
    var_dump($data);

});
// app/routes.php

Route::get('/', function()
{

    $data = Input::except('category','blog');
    var_dump($data);

});

Our POST and GET request data is only available for a single request. Laravel provides a method where you can save the request data more than on request. let's see how we can do that with an example.

// app/routes.php

Route::get('/', function()
{
  
   Input::flash();
   return Redirect::to('new/request');

}

Route::get('new/request', function()
{
  
  var_dump(Input::old());

}

The Input::old() method tells laravel that we want entire data that we flashed in the previous request. Just like the get(), only() and except() methods, the old(), falshOnly() and falshExcept() methods accept pair of parameters or an array.

Till now we got the request data and we have retrieved the data using lot of methods in whatever way we want it based on the situation. Now suppose we got request data after submitting a form. But there was some error so we need to send back the user to the same form and we have to the populate the form with the data he submitted previously. To do this laravel provides a method called withInput().

Let's see how we can use this method in routes.

// app/routes.php

Route::get('/', function()
{

    return Redirect::to('new/request')->withInput();

});

Sometimes you need to send only certain data back to the user like in a case where user login. We need to send only email back to the user when something wrong, in those cases we can Input::only() method with withInput() method like below.

// app/routes.php

Route::get('/', function()
{

    return Redirect::to('new/request')->withInput(Input::only('email'));

});

In the same way you can also use except() method based on the requirement in the application.

Till now we saw how to process the data, but all the data was textual data only. But this is not the single data web applications is going to get in the request. We can also receive files that have been uploaded as a part of multi part encoded form.

Let's create a form to upload a file using POST method.

// app/views/form.blade.php

<form action="{{ url('hanlde-form') }}" enctype="multipart/form-data" method="POST">

   <input name="book" type="file" /> 
  
  <input form="" type="submit" />

</form>

Once the form was submitted to extract the uploaded file we have to use Input::file() method to know about the file details.There are lot of methods we can use to know certain parameters of the uploaded file.

Input::file('book')->getFileName();

Input::file('book')->getClientOriginalName();

Input::file('book')->getClientSize();

Input::file('book')->getMimeType();

Input::file('book')->guessExtension();

Input::file('book')->getRealPath();

Input::file('book')->move('destination/path');

To move the uploaded file using the above methods to particular directory, let's see how we can do that.

// app/routes.php

Route::post('post-form', function() {
  
 $name = Input::file('book')->getClientOriginalName();

 Input::file('book')->move('destination/path', $name);

 return 'File Moved!';

}

Request Information

The Request class provides many methods to examine certain information about the request methods. Let's see those methods.

// Retrieving the request URI
$uri = Request::path();

//Retrieving the request method
$method = Request::method();

if(Request::isMethod('post'))
{

   //code will go here

}

// determining if the request path matches a pattern
if(Request::is('admin/*'))
{

   //code will go there

}

//get the request url
$url = Request::url();

//retrieve a request URI segment
$segment = Request::segment(1);

// determining if the request is over HTTPS
if(Request::secure())
{

   //code will go there

}

// determining if the request is using Ajax
if(Request::ajax())
{

   //code will go there

}

// determining if the request has JSON content type
if(Request::isJson())
{

   //code will go there

}

Cookies

All cookies created by the laravel framework are encrypted and signed with an authentication code, meaning they will be considered invalid if they have been changed by the client.

Retrieving a cookie value

$value = Cookie::get('name');

Attaching a new cookie to a response

$response = Response::make('Hello World!');

$response->withCookie(Cookie::make('name','value', $minutes);

Creating a cookie that lasts forever

$cookie= Cookie::forever('name','value');

These are the some of the requests and inputs methods we can use when we are working on laravel framework data retrieval. 

Thanks

KodeInfo

Author

  • Imran Iqbal
    Imran Iqbal

    Imran is a web developer and consultant from India. He is the founder of KodeInfo, the PHP and Laravel Community . In the meantime he follows other projects, works as a freelance backend consultant for PHP applications and studies IT Engineering . He loves to learn new things, not only about PHP or development but everything.

Related

WHY USE A FRAMEWORK OVER PLAIN PHP

WHY USE A FRAMEWORK OVER PLAIN PHP
read more

GETTING STARTED WITH LARAVEL

GETTING STARTED WITH LARAVEL
read more

UNDERSTANDING LARAVEL STRUCTURE

UNDERSTANDING LARAVEL STRUCTURE
read more

UNDERSTANDING LARAVEL ROUTES

UNDERSTANDING LARAVEL ROUTES
read more

comments powered by Disqus