HTTP Requests

HTTP Requests

Instructor-svgAl-Mamun Sarkar
Jul 08 , 2020

In this lesson, I will show you how to use request in laravel applications.

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class TestController extends Controller
{
   public function store(Request $request)
    {
        //
    }
}

 

Request Via Route Closures:

use Illuminate\Http\Request;

Route::get('/', function (Request $request) {
    //
});

 

Retrieving The Request Path:

$uri = $request->path();

 

Request Method:

$method = $request->method();

if ($request->isMethod('post')) {
    //
}

 

Retrieving Input Data:

$input = $request->all();
$name = $request->input('name');
$name = $request->input('name', 'Sally'); // With default value

 

Check :

if ($request->has('name')) {
    //
}

if ($request->has(['name', 'email'])) {
    //
}

 

Validate Data:

 $data = $request->validate([
    'title' => 'required|unique:posts|max:255',
    'body' => 'required',
]);

 

Displaying The Validation Errors:

@if ($errors->any())
    <div class="alert alert-danger">
        <ul>
            @foreach ($errors->all() as $error)
                <li>{{ $error }}</li>
            @endforeach
        </ul>
    </div>
@endif

 

The @error Directive:

<label for="title">Post Title</label>

<input id="title" type="text" class="@error('title') is-invalid @enderror">

@error('title')
    <div class="alert alert-danger">{{ $message }}</div>
@enderror

 

Optional Fields:

$request->validate([
    'publish_at' => 'nullable|date',
]);

 

 Create Custom Request:

php artisan make:request MyTestRequest
public function rules()
{
    return [
        'title' => 'required|unique:posts|max:255',
        'body' => 'required',
    ];
}

 

  • Share On:
  • fb
  • twitter
  • pinterest
  • instagram