How to create, read, update and delete files in Laravel?
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?
- This code will create a file called
myfile.txt
. - Write the text “Hello, world!” to it.
- Read the contents of the file and print it to the screen
- Update the contents of the file to “Hello, world! How are you today?”.
- Delete the file.
- Check if the file exists.
- 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);