Table of Contents
Laravel is a powerful and popular PHP framework that provides many useful tools and features for web development. One of the common features of many websites and web applications is a gallery or image management system. With Laravel, developers can easily build and manage image galleries using various techniques and packages.
There are several benefits to using Laravel for gallery management, including the ability to leverage the framework's built-in functionality for image manipulation and storage. Additionally, there are many third-party packages available for Laravel that provide advanced image management features, such as cropping, resizing, and watermarking.
In this context, gallery management refers to the process of creating, editing, and displaying a collection of images in a web application. This can involve creating a backend interface for adding and organizing images, as well as front-end functionality for displaying the images in an attractive and user-friendly manner.
This tutorial teaches you how to do Laravel gallery managements with the Intervention Image library. The library simplifies image creation, editing, and composition using ServiceProviders and Facades.
By the end of this tutorial, you will be able to open, resize and save images with the library.
// open an image
$image = Image::make(<image_path>);
// resize an image
$image->resize(<width>, <height>);
// save an image
$image->save(<image_path/format>);
Let's start by creating a Laravel application and the Post model with a table.
Creating a Gallery Management System in Laravel
The code laravel new gallery
creates a new Laravel project named "gallery". The cd gallery
command moves the current directory to the newly created Laravel project's directory.
The next command php artisan make:model Post -m
creates a new model named "Post" and a corresponding migration file. The "-m
" flag indicates that a migration file should be created with the model.
Lastly, composer require intervention/image
installs the Intervention Image package, which is a popular image handling library for Laravel. It allows for image resizing, cropping, and other image manipulations.
laravel new gallery cd gallery php artisan make:model Post -m composer require intervention/image
We created a new Laravel application and navigated into it. Next, we made the Post model with its migration file. Lastly, we installed the Intervention Image library. Let's configure the image library.
Open the project in a code editor like Visual Studio Code and add the following lines in the respective arrays of the config/app.php
file.
// providers
Intervention\Image\ImageServiceProvider::class,
// aliases
'Image' => Intervention\Image\Facades\Image::class,
With the configurations, we can use the Intervention Image library like any other Facade class; the only difference is that we don't have to import the class in the target file manually.
Next, let's write the posts table, routes, and views.
Update Schema
Create the database as configured in the .env
file, then add the following schema record in the posts table in the database/migrations
file.
$table->string('image');
Uploading and Storing Images
Open the routes/web.php
file and write the /store
and /
routes.
Create
The code uses a post route to handle the file upload, which accepts an array of images. It then iterates over each image in the array and uses the Intervention Image package to create a new image resource from the uploaded file.
After creating the image resource, it extracts the image name, defines the file path to public/images, resizes the image to 300 x 200 pixels, and saves the image. It then saves the image name to the database in the posts table using the Post model.
Finally, the code returns a redirect to the homepage. This is a simple example of how to upload and store images in Laravel's gallery management system, and it can be adapted to suit specific needs by modifying the image size, file path, and database table name.
Route::post('/store', function(Request $request) {
$files = $request->file('images');
foreach ($files as $file) {
// creating a new image resource from a file
$img = Image::make($file->getRealPath());
// extract image name
$img_name = $file->getClientOriginalName();
// define file path => public/images
$img_path = public_path('images');
// resize and save the image.
$img->resize(300, 200)->save($img_path.'/'.$img_name);
// save the image to the posts table
$post = new Post();
$post->image = $img_name;
$post->save();
}
return redirect('/');
});
We upload multiple image files from a form
The form method is set to POST and the enctype attribute is set to multipart/form-data
since we are dealing with files.
The form contains an input element with type="file"
which allows users to select one or multiple image files to upload. The name
attribute is set to images[]
to indicate that the uploaded files will be an array.
A CSRF token is included using the @csrf
directive which is a security measure to prevent cross-site request forgery attacks.
<form action="{{ url('/store') }}" method="post" enctype="multipart/form-data">
@csrf
<div>
<input type="file" name="images[]" id="image" multiple>
<button>Save</button>
</div>
</form>
And loop through the files, creating a new image resource from a file, extracting the image name, and defining its upload destination before resizing and saving the image in the location.
Lastly, we store the image in the database. Note: create the public/images
directory before saving the images in the file path.
Read
This code defines a route with the GET method, which returns the welcome view with the latest posts in descending order. The Post::latest()
method is used to retrieve the posts ordered by their created_at timestamp in descending order. The get()
method retrieves all of the records from the database table.
The compact()
function is used to create an array of data to be passed to the view. In this case, the $posts
variable is passed to the view, which will be available as a variable within the view. The view is returned using the view()
function, which expects the name of the view as its first argument and an array of data as the second argument.
Route::get('/', function () {
$posts = Post::latest()->get();
return view('welcome', compact('posts'));
});
This code displays all the images stored in the "public/images" folder and their corresponding details in a loop. It first defines a <div>
container and then uses a @foreach
loop to iterate over each post in the $posts
variable.
Inside the loop, it displays the image by setting its source to asset('images/'. $post->image)
, which generates the correct path to the image in the "public/images" folder. The asset
function is a Laravel helper function that generates a URL to the specified asset.
By default, the asset
function generates an HTTP URL for the asset, but you can use the secure_asset
function instead to generate an HTTPS URL.
<div>
@foreach($posts as $post)
<img src="{{ asset('images/'. $post->image) }}">
@endforeach
</div>
Testing
Start the development server and migrate the changes
php artisan migrate
php artisan serve
before creating and displaying images at the http://127.0.0.1:8000
address.
Although we did not resize the images on the client-side, the Intervention Image library resized and saved the images in the public directory.
Summary
In summary, Laravel is a popular PHP framework that makes building web applications easier and faster. One common use case for Laravel is building a gallery management system, which involves uploading and storing images and then displaying them on a webpage.
To accomplish this, we can use the Intervention Image library, which provides a simple way to manipulate images in PHP. After installing the library via Composer, we can use it to open, resize, and save images.
In our example code, we use a POST route to handle image uploads. We extract the uploaded files, create an Intervention Image resource from each file, resize and save the image, and then store the image name in our database. In the view, we use a loop to display all the stored images on the webpage.
Overall, Laravel's built-in features and third-party libraries like Intervention Image make it easy to build a robust gallery management system. By leveraging Laravel's routing, database models, and view templating, we can create a simple and effective system for managing and displaying images.
You can find more ways to use the package on the official documentation.