Cloudinary Blog

Associating Media Files With Laravel’s Eloquent Models

Associating Media Files With Laravel’s Eloquent Models

Laravel, currently the most popular PHP framework, offers databases an efficient, well-written Active Record implementation, called the Eloquent Object-Relational Mapper (ORM). Specifically, Eloquent maps a database table to an Eloquent model along with fluent methods and expressions for querying and modifying the database’s records.

Given that you as web developers routinely and frequently upload, download, and transform media files, being able to efficiently associate them with your Laravel Eloquent models saves time and resources. This tutorial describes that process, step by step, with code examples.

Set Up a Laravel Project

  1. Install Composer and PHP on your development or production machine and then run this command:

    Copy to clipboard
    composer create-project --prefer-dist laravel/laravel project
  2. Go to the project directory and rename the env.example file to .env.

  3. Run the project with the command php artisan serve.

Your Laravel project is now up and running.

Set Up Cloudinary’s Laravel SDK

  1. Install Cloudinary’s Laravel SDK:

    Copy to clipboard
    composer require cloudinary-labs/cloudinary-laravel

    Note: Be sure to follow the steps in the #Installation section. Publish the configuration file and add your Cloudinary credentials to the .env file of your app.

  2. Publish the migration file in Cloudinary’s Laravel SDK with this command:

    Copy to clipboard
    php artisan vendor:publish --provider="CloudinaryLabs\CloudinaryLaravel\CloudinaryServiceProvider" --tag="cloudinary-laravel-migration"
  3. Run php artisan migrate to create the required media table in your database. Verify that the table is in place afterwards.

    Before uploading files to Cloudinary, sign up for a free Cloudinary account, log in, and note your cloud name and API keys from the dashboard.

media library

Set Up the Mechanics for Attaching Media

Follow the two steps below to attach media to a webpage, which can accept as many as you desire as thumbnails or as files. Follow these two steps:

  1. Create with Laravel migrations a pages table with two fields, id and body, in your database.

  2. Create the Page model that maps to the pages database table:

Copy to clipboard
<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Page extends Model
{

    /**
    * The table associated with the model.
    *
    * @var string
    */
    protected $table = 'pages';
}

Set Up the Mechanics for Attaching Files to Laravel Eloquent Models

Next, import the CloudinaryLabs\CloudinaryLaravel\MediaAlly trait into your model so that you can attach media files to the Eloquent model:

Copy to clipboard
<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use CloudinaryLabs\CloudinaryLaravel\MediaAlly;

class Page extends Model
{
    use MediaAlly;

    ...
}

App\Models\Page.php

Attach, Retrieve, Or Delete Media Files

You can now attach media files to the Page model in your Laravel controller. Below are three use cases. The first two assume that you’re uploading the files as attachments for the first time

First Use Case

Create a page and then attach files to it:

Copy to clipboard
...
$page = Page::create($this->request->input());
$page->attachMedia($file);   // Example of $file is $request->file('file');
...

To verify, check the media table in your database for a new record that looks like this:

media table

Second Use Case

Fetch an existing page and attach media files to it:

Copy to clipboard
...
$page = Page::find(2);
$page->attachMedia($file);   // Example of $file is $request->file('file');
...

Third Use Case

In this instance, you’ve already uploaded to Cloudinary or another cloud storage the media files to be attached to a page. Call the attachRemoteMedia method:

Copy to clipboard
...
$page = Page::create($this->request->input());
$page->attachRemoteMedia($existingRemoteUrl); 
...
Copy to clipboard
...
$page = Page::find(2);
$page->attachRemoteMedia($existingRemoteUrl);  
...

File Retrieval

You can retrieve all the files you’ve attached to the Page record, or just the first or last file.

To retrieve all the files that are attached to the Page record:

Copy to clipboard
...
$filesBelongingToSecondPage = Page::find(2)->fetchAllMedia();
...

To retrieve the first file that’s attached to the Page record:

Copy to clipboard
...
$fileBelongingToSecondPage = Page::find(2)->fetchFirstMedia();
...

To retrieve the last file that’s attached to the Page record:

Copy to clipboard
...
$fileBelongingToSecondPage = Page::find(2)->fetchLastMedia();
...

File Deletion

To delete all the files you’ve attached to the Page record:

Copy to clipboard
...
$page = Page::find(2);
$page->detachMedia();
...

Leverage More Cloudinary Capabilities

Uploading and attaching files barely scratches the surface of media management. Cloudinary helps you administer the entire spectrum of your media’s lifecycle, end to end, from upload and transformation to optimization and delivery. Do check it out.

Recent Blog Posts

Automation Frees Up PetRescue’s Staff to Help Pets Find Their Forever Homes

As we spend more time at home, many of us are adopting pets for the joy, companionship and a surprising range of health benefits. In Australia, where our nonprofit customer PetRescue is located, there’s a shortage of pets to adopt. Last August, the Guardian reported that dog shelters in Australia emptied and adoption fees for puppies were running as high as $AUS1800.

Read more
Cloudinary and Contentful Make Modern Content Management Easier

I am pleased to share that Cloudinary and Contentful have joined forces to further streamline the creation, processing, and delivery of online content through Cloudinary’s digital asset management (DAM) solution and advanced transformation and delivery capabilities for images and video. What’s more, the partnership delivers a headless approach to DAM. By leveraging APIs for media management tasks, marketers and developers alike benefit from an integrated stack of optimized assets for optimization and automation. As a result, page loads are fast and beautiful, and at scale—with less overhead and effort.

Read more
Introducing Cloudinary's Nuxt Module

Since its initial release in October 2016 by the Chopin brothers as a server-side framework that runs on top of Vue.js, Nuxt (aka Nuxt.js) has gained prominence in both intuitiveness and performance. The framework offers numerous built-in features based on a modular architecture, bringing ease and simplicity to web development. Not surprisingly, Nuxt.js has seen remarkable growth in adoption by the developer community along with accolades galore. At this writing, Nuxt has earned over 30K stars on GitHub and 96 active modules with over a million downloads per month. And the upward trend is ongoing.

Read more
How Quality and Quantity can go Hand in Hand

When it comes to quality versus quantity, you’ll often hear people say, “It’s the quality that counts, not the quantity”. While that’s true in many situations, there are also cases where you want both quality and quantity. You may have thousands of images on your website and you want them all to look great. This is especially important if your website allows users to upload their own content, for example, to sell their own products or services. You don't want their poor quality images to reflect badly on your brand.

Read more
Product Videos 101: What Makes Them Great?

A product’s benefits and usage, including its value proposition, features, and instructive details, are best demonstrated through video. Product-video types vary, depending on the funnel, channel, and audience, the most popular ones being demos, reviews, installation, and how-tos.

Read more