Laravel Course

- Retrieving Input data from form

To can obtain an instance of the current HTTP request in a controller, you should use the Illuminate\Http\Request class in your controller, and the Request $request parameter in controller method.
If the controller method is also expecting input from a route parameter you should list your route parameters after $request parameter.
- For example, if a "test" route is defined like so:
Route::name('test')->get('test/{id}', 'TestController@index');
A TestController class in a "TestController.php" file (in app/Http/Controllers/ directory) might look like this:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;

class TestController extends Controller {

  //Responds to requests to /test
  //receives the $request instane, $id from URI
  //returns view() response
  public function index(Request $request, $id){
    return view('test');
  }
}

Request Path and Method

The $request object provides a variety of methods for examining the HTTP request.
See this page for a complete List with Request Methods

- Example:
1. Add the following code in the "TestController.php" file:
namespace App\Http\Controllers;
use Illuminate\Http\Request;

class TestController extends Controller {

  //Responds to requests to /test
  //receives the $request instance, $id from URI
  //returns view() response
  public function index(Request $request, $name=''){
    //Usage of is() method
    $is_uri = $request->is('test/*');

    //set array with keys to be passed to view() for template
    $data =[
      'name'=>$name,
      'uri'=>$request->path(),
      'url'=>$request->url(),
      'is_uri'=>$is_uri ?'URI matches the "test/*" pattern' :'URI not matches the "test/*" pattern',
      'method'=>$request->method()
    ];

    return view('test', $data);
  }
}
2. Add the following code in a file "test.blade.php" (in the "resources/views/" folder):
<!doctype html>
<html lang="{{app()->getLocale()}}">
<head>
<meta charset="utf-8">
<title>Test Page</title>
</head>
<body>
<h1>Test page</h1>
NAME ARGUMENT: {{$name}}<br>
URI: {{$uri}}<br>
URL: {{$url}}<br>
METHOD: {{$method}}<br>
is() METHOD: {{$is_uri}}
</body>
</html>
3. Add the following line in the "routes/web.php" file:
Route::name('test_pg')->get('/test/{name?}', 'TestController@index');
4. Visit the following URL:
//localhost:8000/test/peace
- The output will appear as shown in the following image.
laravel request path methods

Retrieving Input data from form

No matter what method was used GET or POST, the Laravel method will retrieve input values for both the methods the same way. You can retrieve the input values using either of these variantes:

Determining if an Input Value is Present

It is indicated to use the has() method to determine if a value is present on the request.
The has() method returns true if the value is present:
if($request->has('name')){
  //
}
When given an array, the has() method will determine if all of the specified values are present:
if($request->has(['name', 'email'])){
  //
}

- Example:
1. Add the following code in the "TestController.php" file (in app/Http/Controllers/ directory):
namespace App\Http\Controllers;
use Illuminate\Http\Request;

class TestController extends Controller {

  //Responds to requests to /test
  //receives the $request instance, $id from URI
  //returns view() response
  public function index(Request $request, $name=''){
    //Usage of is() method
    $is_uri = $request->is('test/*');

    //set array with keys to be passed to view() for template
    $data =[
      'name'=>$name,
      'uri'=>$request->path(),
      'url'=>$request->url(),
      'is_uri'=>$is_uri ?'URI matches the "test/*" pattern' :'URI not matches the "test/*" pattern',
      'method'=>$request->method()
    ];

    return view('test', $data);
  }

  //Responds to post requests to /user/register
  //receives the $request instance
  //outputs input fields data, or message
  public function userRegister(Request $request){
    //if required fields are received, and not empty
    if($request->has(['name', 'username', 'password']) && $request->name!=null && $request->username!=null && $request->password!=null){
      //Retrieve the name input field
      $name = $request->input('name');
      echo 'Name: '.$name .'<br>';

      //Retrieve the username input field
      $username = $request->username;
      echo 'Username: '.$username .'<br>';

      //Retrieve the password input field
      $password = $request->password;
      echo 'Password: '.$password;
    }
    else echo 'Please fill all the form fields';
  }
}
2. Create a "register_form.blade.php" file in the "resources/views/" folder, with this code:
<form method="post" action="/user/register">
{{ csrf_field() }}
<label>Name: <input type='text' name='name'/></label><br>
<label>Username: <input type='text' name='username'/></label><br>
<label>Password: <input type='password' name='password'/></label><br>
<input type='submit' value='Register'/>
</form>
The {{ csrf_field() }} statement adds a "hidden" input field in the form. That field contains the CSRF "token", which is automatically generated by Laravel framework to protect the application from cross-site request forgery (CSRF) attacks.
You should use the {{ csrf_field() }} statement to include a hidden CSRF token field in each form so that the CSRF protection middleware can validate the request.
3. Add the following code in the "routes/web.php" file:
//shows the register form
Route::get('/register',function(){
  return view('register_form');
});

//when the register form is submited
Route::post('/user/register', 'TestController@userRegister');
4. Visit the following URL, and add some data in form fields:
//localhost:8000/register
- It will display a page like in this image:
laravel request test register
5. Click Register button, it will open a page with the user registration details, as shown in the following image:
laravel request user data

- Documentation: Laravel - Requests

Daily Test with Code Example

HTML
CSS
JavaScript
PHP-MySQL
Which tag is used to add lists into <ul> and <ol> elements?
<dt> <dd> <li>
<ul>
 <li>http://coursesweb.net/html/</li>
 <li>http://coursesweb.net/css/</li>
</ul>
Which value of the "display" property creates a block box for the content and ads a bullet marker?
block list-item inline-block
.some_class {
  display: list-item;
}
Which instruction converts a JavaScript object into a JSON string.
JSON.parse() JSON.stringify eval()
var obj = {
 "courses": ["php", "javascript", "ajax"]
};
var jsonstr = JSON.stringify(obj);
alert(jsonstr);    // {"courses":["php","javascript","ajax"]}
Indicate the PHP class used to work with HTML and XML content in PHP.
stdClass PDO DOMDocument
$strhtml = '<body><div id="dv1">CoursesWeb.net</div></body>';
$dochtml = new DOMDocument();
$dochtml->loadHTML($strhtml);
$elm = $dochtml->getElementById("dv1");
echo $elm->nodeValue;    // CoursesWeb.net
Requests

Last accessed pages

  1. PHP getElementById and getElementsByTagName (49471)
  2. Mysql SELECT JOIN tables on two different Databases (4498)
  3. jQuery UI draggable - Drag elements (11448)
  4. Courses Web: PHP-MySQL JavaScript Node.js Ajax HTML CSS (142520)
  5. Using the Bone Tool (4253)

Popular pages this month

  1. Courses Web: PHP-MySQL JavaScript Node.js Ajax HTML CSS (523)
  2. The Mastery of Love (65)
  3. CSS cursor property - Custom Cursors (62)
  4. Read Excel file data in PHP - PhpExcelReader (59)
  5. PHP-MySQL free course, online tutorials PHP MySQL code (44)