create, read, update and delete files in Laravel

How to create, read, update and delete files in Laravel?

0 / 0 2 Mins Admin

December 23, 2022

10 Comments

We will write beginner-friendly Laravel CRUD operations. We will show you how to make CRUD files in Laravel in with basic examples. In Laravel, you can use the File facade and the built-in PHP functions to create, read, update, and delete files.

The File facade

Here are a few examples of how you can use the File facade and the built-in PHP functions to create, read, update, and delete a file in Laravel:

use Illuminate\Support\Facades\File;

// Create a file
File::put('myfile.txt', 'Hello, world!');

// Read a file
$contents = File::get('myfile.txt');
echo $contents;

// Update a file
File::put('myfile.txt', 'Hello, world! How are you today?');

// Delete a file
File::delete('myfile.txt');

// Check if a file exists
if (File::exists('myfile.txt')) {
    echo "The file exists.";
} else {
    echo "The file does not exist.";
}

// Check if a file is writable
if (File::isWritable('myfile.txt')) {
    echo "The file is writable.";
} else {
    echo "The file is not writable.";
}

How does the above code work?

  1. This code will create a file called myfile.txt.
  2. Write the text “Hello, world!” to it.
  3. Read the contents of the file and print it to the screen
  4. Update the contents of the file to “Hello, world! How are you today?”.
  5. Delete the file.
  6. Check if the file exists.
  7. Check if the file is writable.

The File facade provides an interface with built-in PHP functions for working with files. If you want, you can use the built-in PHP functions directly.

Here is an example of how to use built-in PHP functions to execute CRUD (create, read, update, delete) actions on a file:

Built-in PHP functions for CRUD(create, read, update, delete) actions on a file.

// Create a new file
$file = 'file_name.txt';
touch($file);

// Write to the file
$text = "This is some text that will be written to the file.";
$handle = fopen($file, 'w');
fwrite($handle, $text);
fclose($handle);

// Read from the file
$handle = fopen($file, 'r');
$contents = fread($handle, filesize($file));
echo $contents;
fclose($handle);

// Update the file
$text = "This is an updated version of the text in the file.";
$handle = fopen($file, 'w');
fwrite($handle, $text);
fclose($handle);

// Read from the file again to verify the update
$handle = fopen($file, 'r');
$contents = fread($handle, filesize($file));
echo $contents;
fclose($handle);

// Delete the file
unlink($file);