Backend Development 5 min read

Handling Cookies and File Uploads in Laravel

This article explains how Laravel encrypts and signs cookies to prevent tampering, shows multiple ways to set and retrieve cookie values, and provides detailed instructions and code examples for uploading, validating, and storing files using the framework's request and response utilities.

php中文网 Courses
php中文网 Courses
php中文网 Courses
Handling Cookies and File Uploads in Laravel

Laravel encrypts cookie values and signs them with an authentication code, so any client‑side modification will invalidate the cookie and prevent forgery.

To set a cookie you can use the cookie('name', 'value', $minutes) helper and return it with response('text')->cookie($cookie) , or call response('text')->cookie('name', 'value', $minutes) directly.

Cookies can be retrieved either via the request instance $value = $request->cookie('name'); or using the facade $value = Cookie::get('name'); .

Uploaded files are accessed with $file = $request->file('logo'); or the dynamic property $file = $request->logo; . Before using the file you can check its presence with if ($request->hasFile('logo')) { ... } and validate it with if ($request->file('logo')->isValid()) { ... } .

The uploaded file object provides methods such as $file->path() to get the temporary path and $file->extension() to obtain the file extension.

Files are stored using the $file->store('directory') method, which saves the file on a configured disk (local, public, s3, etc.) as defined in config/filesystems.php . The configuration array lists the available disks and their drivers.

To specify a custom filename, use $request->file('logo')->storeAs('img/logo', '1.png'); , where the second argument is the desired filename.

Below is a complete example: an HTML form for uploading a file and the corresponding controller code that checks the file, generates a unique name, stores it with storeAs , and outputs the stored path.

<form method="post" action="/index?a=32" enctype="multipart/form-data">
    @csrf
    <input type="file" name="logo">
    <input type="submit" value="sub" />
</form>
if ($request->hasFile('logo')) {
    $logo = $request->file('logo');
    if ($logo->isValid()) {
        $ext = $logo->extension();
        $fileName = date('YmdHis') . mt_rand(10000,99999);
        $path = $logo->storeAs('img/logo', $fileName . '.' . $ext);
        dump($path); // e.g., "img/logo/2020121413351718218.png"
    }
}
BackendFile UploadPHPcookiesLaravelresponse
php中文网 Courses
Written by

php中文网 Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.