Javascript required
Skip to content Skip to sidebar Skip to footer

Laravel Check if Array Has Uploaded File

Icon

Alert You're browsing the documentation for an one-time version of Laravel. Consider upgrading your projection to Laravel 9.ten.

HTTP Requests

  • Accessing The Asking
    • Basic Request Information
    • PSR-7 Requests
  • Retrieving Input
    • One-time Input
    • Cookies
    • Files

Accessing The Asking

To obtain an instance of the current HTTP request via dependency injection, y'all should type-hint the Illuminate\Http\Request grade on your controller constructor or method. The electric current request case volition automatically be injected past the service container:

                                              

<?php

namespace App\Http\Controllers;

employ Illuminate\Http\ Request ;

class UserController extends Controller

{

/**

* Shop a new user.

*

* @param Asking $request

* @return Response

*/

public function store ( Request $request )

{

$name = $asking -> input ( ' proper name ' );

//

}

}

If your controller method is also expecting input from a route parameter, but list your route arguments after your other dependencies. For example, if your route is defined like then:

                                              

Road :: put ( ' user/{id} ' , ' [e-mail protected] ' );

You may yet blazon-hint the Illuminate\Http\Request and access your route parameter id by defining your controller method like the following:

                                              

<?php

namespace App\Http\Controllers;

apply Illuminate\Http\ Request ;

form UserController extends Controller

{

/**

* Update the specified user.

*

* @param Request $request

* @param string $id

* @return Response

*/

public function update ( Request $request , $id )

{

//

}

}

Bones Request Information

The Illuminate\Http\Request example provides a diversity of methods for examining the HTTP asking for your application and extends the Symfony\Component\HttpFoundation\Request class. Here are a few more than of the useful methods available on this form:

Retrieving The Asking URI

The path method returns the request's URI. So, if the incoming request is targeted at http://domain.com/foo/bar, the path method will return foo/bar:

                                              

$uri = $request -> path ();

The is method allows you to verify that the incoming request URI matches a given blueprint. You may use the * character equally a wildcard when utilizing this method:

                                              

if ( $request -> is ( ' admin/* ' )) {

//

}

To go the full URL, not simply the path info, y'all may use the url or fullUrl methods on the request example:

                                              

// Without Query String...

$url = $request -> url ();

// With Query Cord...

$url = $request -> fullUrl ();

You may also go the full URL and append query parameters. For example, if the request is targeted at http://domain.com/foo, the following method will return http://domain.com/foo?bar=baz:

                                              

$url = $asking -> fullUrlWithQuery ([ ' bar ' => ' baz ' ]);

Retrieving The Asking Method

The method method will return the HTTP verb for the request. You may as well utilise the isMethod method to verify that the HTTP verb matches a given cord:

                                              

$method = $asking -> method ();

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

//

}

PSR-7 Requests

The PSR-7 standard specifies interfaces for HTTP messages, including requests and responses. If yous would like to obtain an example of a PSR-7 asking, you will first need to install a few libraries. Laravel uses the Symfony HTTP Message Span component to convert typical Laravel requests and responses into PSR-7 compatible implementations:

                                              

composer require symfony / psr - http - bulletin - bridge

composer crave zendframework / zend - diactoros

Once you lot take installed these libraries, you may obtain a PSR-7 request by simply type-hinting the request type on your route or controller:

                                              

use Psr\Http\Bulletin\ ServerRequestInterface ;

Road :: become ( ' / ' , office ( ServerRequestInterface $request ) {

//

});

If y'all return a PSR-7 response instance from a road or controller, it volition automatically be converted back to a Laravel response instance and be displayed by the framework.

Retrieving Input

Retrieving An Input Value

Using a few simple methods, y'all may access all user input from your Illuminate\Http\Request instance. You exercise non need to worry about the HTTP verb used for the request, as input is accessed in the aforementioned fashion for all verbs:

                                              

$name = $asking -> input ( ' name ' );

Y'all may laissez passer a default value equally the second argument to the input method. This value volition be returned if the requested input value is not present on the request:

                                              

$name = $request -> input ( ' proper noun ' , ' Sally ' );

When working on forms with array inputs, yous may use "dot" notation to access the arrays:

                                              

$name = $request -> input ( ' products.0.name ' );

$names = $request -> input ( ' products.*.proper noun ' );

Retrieving JSON Input Values

When sending JSON requests to your application, you lot may admission the JSON data via the input method equally long as the Content-Type header of the request is properly set to application/json. Y'all may even employ "dot" syntax to dig deeper into JSON arrays:

                                              

$name = $request -> input ( ' user.name ' );

Determining If An Input Value Is Nowadays

To determine if a value is nowadays on the asking, you may utilize the has method. The has method returns true if the value is nowadays and is not an empty cord:

                                              

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

//

}

Retrieving All Input Information

You may likewise retrieve all of the input data as an array using the all method:

                                              

$input = $request -> all ();

Retrieving A Portion Of The Input Data

If you demand to think a sub-set of the input data, you may use the only and except methods. Both of these methods volition have a single array or a dynamic list of arguments:

                                              

$input = $request -> only ([ ' username ' , ' password ' ]);

$input = $request -> simply ( ' username ' , ' password ' );

$input = $request -> except ([ ' credit_card ' ]);

$input = $asking -> except ( ' credit_card ' );

Dynamic Properties

You may also admission user input using dynamic properties on the Illuminate\Http\Request instance. For example, if ane of your application's forms contains a name field, you may admission the value of the posted field similar and so:

                                              

$name = $request ->proper name ;

When using dynamic properties, Laravel will first expect for the parameter's value in the request payload and then in the route parameters.

Old Input

Laravel allows you to go on input from one request during the adjacent request. This characteristic is particularly useful for re-populating forms afterward detecting validation errors. However, if you are using Laravel's included validation services, information technology is unlikely you will need to manually use these methods, every bit some of Laravel's congenital-in validation facilities will call them automatically.

Flashing Input To The Session

The wink method on the Illuminate\Http\Request instance will flash the electric current input to the session so that information technology is bachelor during the user'due south next request to the application:

                                              

$request -> flash ();

You may also use the flashOnly and flashExcept methods to wink a sub-set of the request data into the session:

                                              

$request -> flashOnly ([ ' username ' , ' electronic mail ' ]);

$request -> flashExcept ( ' password ' );

Wink Input Into Session Then Redirect

Since you oft will want to wink input in clan with a redirect to the previous page, you may easily concatenation input flashing onto a redirect using the withInput method:

                                              

return redirect ( ' class ' ) -> withInput ();

return redirect ( ' form ' ) -> withInput ( $request -> except ( ' password ' ));

Retrieving Old Data

To retrieve flashed input from the previous request, use the old method on the Request instance. The old method provides a convenient helper for pulling the flashed input information out of the session:

                                              

$username = $request -> former ( ' username ' );

Laravel also provides a global old helper office. If you are displaying old input within a Blade template, it is more user-friendly to use the quondam helper. If no old input exists for the given string, goose egg will exist returned:

                                              

< input type = " text " proper noun = " username " value = " {{ old('username') }} " >

Cookies

Retrieving Cookies From The Request

All cookies created past the Laravel framework are encrypted and signed with an authentication code, meaning they will exist considered invalid if they have been changed by the client. To think a cookie value from the request, you may utilise the cookie method on the Illuminate\Http\Asking example:

                                              

$value = $asking -> cookie ( ' name ' );

Attaching A New Cookie To A Response

Laravel provides a global cookie helper function which serves as a simple manufactory for generating new Symfony\Component\HttpFoundation\Cookie instances. The cookies may be attached to a Illuminate\Http\Response instance using the withCookie method:

                                              

$response = new Illuminate\Http\ Response ( ' Hello World ' );

$response -> withCookie ( ' proper name ' , ' value ' , $minutes );

return $response ;

To create a long-lived cookie, which lasts for five years, y'all may use the forever method on the cookie factory by first calling the cookie helper with no arguments, and and then chaining the forever method onto the returned cookie factory:

                                              

$response -> withCookie ( cookie () -> forever ( ' name ' , ' value ' ));

Files

Retrieving Uploaded Files

You lot may access uploaded files that are included with the Illuminate\Http\Request instance using the file method. The object returned by the file method is an instance of the Symfony\Component\HttpFoundation\File\UploadedFile grade, which extends the PHP SplFileInfo class and provides a variety of methods for interacting with the file:

                                              

$file = $request -> file ( ' photograph ' );

Yous may determine if a file is nowadays on the request using the hasFile method:

                                              

if ( $request -> hasFile ( ' photograph ' )) {

//

}

Validating Successful Uploads

In addition to checking if the file is present, y'all may verify that in that location were no problems uploading the file via the isValid method:

                                              

if ( $request -> file ( ' photo ' ) -> isValid ()) {

//

}

Moving Uploaded Files

To move the uploaded file to a new location, you should utilise the move method. This method will move the file from its temporary upload location (every bit determined past your PHP configuration) to a more than permanent destination of your choosing:

                                              

$request -> file ( ' photo ' ) -> move ( $destinationPath );

$request -> file ( ' photograph ' ) -> motility ( $destinationPath , $fileName );

Other File Methods

There are a variety of other methods available on UploadedFile instances. Cheque out the API documentation for the class for more information regarding these methods.

stoddardgurhander.blogspot.com

Source: https://laravel.com/docs/5.2/requests