Laravel Unsplash

Laravel Unsplash stats

Downloads
1
Stars
0
Open Issues
0
Forks
0

View on GitHub →

Laravel package for easy integration with the Unsplash API. It allows you to use the Unsplash API in your Laravel applications to fetch photos, collections, and user data.

About Laravel-Unsplash

A Laravel package for easy integration with the Unsplash API. It allows you to use the Unsplash API in your Laravel applications to fetch photos, collections, and user data.

---

Installation

You can install the package via composer:

composer require xchimx/laravel-unsplash

Publish the config file using the artisan CLI tool:

php artisan vendor:publish --provider="Xchimx\UnsplashApi\UnsplashServiceProvider" --tag="config"

finally set the API Key in your ENV file:

UNSPLASH_ACCESS_KEY=your_unsplash_access_key

Optional Rate Limiting settings in ENV file:

UNSPLASH_RATE_LIMITING_ENABLED=true
UNSPLASH_RATE_LIMITING_THRESHOLD=10

Usage

Basic Usage

You can use the UnsplashService in your controllers by injecting it via Dependency Injection:

use Xchimx\UnsplashApi\UnsplashService;
 
class UnsplashController extends Controller
{
protected $unsplashService;
 
public function __construct(UnsplashService $unsplashService)
{
$this->unsplashService = $unsplashService;
}
 
public function search()
{
$photos = $this->unsplashService->searchPhotos('Nature');
 
return view('unsplash.search', compact('photos'));
}
}

Using the Facade

Alternatively, you can use the provided Unsplash facade:

use Xchimx\UnsplashApi\Facades\Unsplash;
 
class UnsplashController extends Controller
{
public function search()
{
$photos = Unsplash::searchPhotos('Nature');
 
return view('unsplash.search', compact('photos'));
}
}

UnsplashService Methods

The UnsplashService provides the following methods:

  1. searchPhotos($query, $perPage = 10, $page = 1)
  2. searchPhotosAdvanced(array $params)
  3. getPhoto($id)
  4. getRandomPhoto(array $params = [])
  5. getPhotoDownloadLink($id)
  6. listCollections($perPage = 10, $page = 1)
  7. getCollection($id)
  8. getUser($username)
  9. getUserPhotos($username, $perPage = 10, $page = 1)
  10. searchCollections($query, $perPage = 10, $page = 1)
  11. withOptions(array $options)

Controller Examples

Here are comprehensive controller examples showing how to use the various methods of the UnsplashService in your Laravel controllers.

1. searchPhotos

namespace App\Http\Controllers;
 
use Illuminate\Http\Request;
use Xchimx\UnsplashApi\Facades\Unsplash;
 
class UnsplashController extends Controller
{
public function search(Request $request)
{
$query = $request->input('query', 'Nature');
$photos = Unsplash::searchPhotos($query);
 
return view('unsplash.search', compact('photos', 'query'));
}
}

Blade View:

@extends('layouts.app')
 
@section('content')
<h1>Photo by {{ $photo['user']['name'] }}</h1>
<img src="{{ $photo['urls']['regular'] }}" alt="{{ $photo['alt_description'] }}">
<p>{{ $photo['description'] ?? 'No description available.' }}</p>
@endsection

2. searchPhotosAdvanced

namespace App\Http\Controllers;
 
use Illuminate\Http\Request;
use Xchimx\UnsplashApi\Facades\Unsplash;
 
class UnsplashController extends Controller
{
public function advancedSearch(Request $request)
{
$params = [
'query' => $request->input('query', 'Nature'),
'color' => $request->input('color'),
'orientation' => $request->input('orientation'),
'per_page' => $request->input('per_page', 15),
'page' => $request->input('page', 1),
];
 
$params = array_filter($params);
 
$response = Unsplash::searchPhotosAdvanced($params);
 
$photos = $response['results'];
 
return view('unsplash.advanced_search', compact('photos', 'params'));
}
}

3. getPhoto

namespace App\Http\Controllers;
 
use Xchimx\UnsplashApi\Facades\Unsplash;
 
class UnsplashController extends Controller
{
public function show($id)
{
$photo = Unsplash::getPhoto($id);
 
return view('unsplash.show', compact('photo'));
}
}

Blade View:

@extends('layouts.app')
 
@section('content')
<h1>Photo by {{ $photo['user']['name'] }}</h1>
<img src="{{ $photo['urls']['regular'] }}" alt="{{ $photo['alt_description'] }}">
<p>{{ $photo['description'] ?? 'No description available.' }}</p>
@endsection

4. getRandomPhoto

namespace App\Http\Controllers;
 
use Xchimx\UnsplashApi\Facades\Unsplash;
 
class RandomPhotoController extends Controller
{
public function show()
{
$photo = Unsplash::getRandomPhoto();
 
return view('photos.random', compact('photo'));
}
}

Blade View:

@extends('layouts.app')
 
@section('content')
<h1>Random Photo</h1>
<img src="{{ $photo['urls']['regular'] }}" alt="{{ $photo['alt_description'] }}">
<p>Photo by {{ $photo['user']['name'] }}</p>
@endsection

5. getPhotoDownloadLink

namespace App\Http\Controllers;
 
use Xchimx\UnsplashApi\Facades\Unsplash;
 
class UnsplashController extends Controller
{
public function download($id)
{
$downloadUrl = Unsplash::getPhotoDownloadLink($id);
 
return redirect($downloadUrl);
}
}

6. listCollections

namespace App\Http\Controllers;
 
use Illuminate\Http\Request;
use Xchimx\UnsplashApi\Facades\Unsplash;
 
class CollectionController extends Controller
{
public function index(Request $request)
{
$page = $request->input('page', 1);
$collections = Unsplash::listCollections(15, $page);
 
return view('collections.index', compact('collections'));
}
}

Blade View:

@extends('layouts.app')
 
@section('content')
<h1>Collections</h1>
@foreach ($collections as $collection)
<div>
<h2>{{ $collection['title'] }}</h2>
<p>{{ $collection['description'] ?? 'No description' }}</p>
<a href="{{ route('collections.show', $collection['id']) }}">View Details</a>
</div>
@endforeach
@endsection

7. getCollection

namespace App\Http\Controllers;
 
use Xchimx\UnsplashApi\Facades\Unsplash;
 
class CollectionController extends Controller
{
public function show($id)
{
$collection = Unsplash::getCollection($id);
 
return view('collections.show', compact('collection'));
}
}

Blade View:

@extends('layouts.app')
 
@section('content')
<h1>{{ $collection['title'] }}</h1>
<p>{{ $collection['description'] ?? 'No description available.' }}</p>
<!-- Display additional details -->
@endsection

8. getUser

namespace App\Http\Controllers;
 
use Illuminate\Http\Request;
use Xchimx\UnsplashApi\Facades\Unsplash;
 
class UserController extends Controller
{
public function user($username, Request $request)
{
$user = Unsplash::getUser($name);
 
return view('user', compact('user'));
}
}

9. getUserPhotos

namespace App\Http\Controllers;
 
use Illuminate\Http\Request;
use Xchimx\UnsplashApi\Facades\Unsplash;
 
class UserController extends Controller
{
public function photos($username, Request $request)
{
$page = $request->input('page', 1);
$photos = Unsplash::getUserPhotos($username, 15, $page);
 
return view('users.photos', compact('photos', 'username'));
}
}

Blade View:

@extends('layouts.app')
 
@section('content')
<h1>Photos by {{ $username }}</h1>
@foreach ($photos as $photo)
<div>
<img src="{{ $photo['urls']['small'] }}" alt="{{ $photo['alt_description'] }}">
<p>{{ $photo['description'] ?? 'No description' }}</p>
</div>
@endforeach
@endsection

10. searchCollections

namespace App\Http\Controllers;
 
use Illuminate\Http\Request;
use Xchimx\UnsplashApi\Facades\Unsplash;
 
class CollectionController extends Controller
{
public function search(Request $request)
{
$query = $request->input('query', 'Nature');
$page = $request->input('page', 1);
 
$collections = Unsplash::searchCollections($query, 15, $page);
 
return view('collections.search', compact('collections', 'query'));
}
}

Blade View:

@extends('layouts.app')
 
@section('content')
<h1>Search Results for Collections: "{{ $query }}"</h1>
@foreach ($collections['results'] as $collection)
<div>
<h2>{{ $collection['title'] }}</h2>
<p>{{ $collection['description'] ?? 'No description' }}</p>
<a href="{{ route('collections.photos', $collection['id']) }}">View Photos</a>
@endforeach
@endsection
</div>

11. withOptions

namespace App\Http\Controllers;
 
use Illuminate\Http\Request;
use Xchimx\UnsplashApi\Facades\Unsplash;
 
class CollectionController extends Controller
{
public function searchWithTimeout(Request $request)
{
// Use withOptions to set custom Guzzle options, e.g., timeout
$photos = Unsplash::withOptions(['timeout' => 2])->searchPhotos('Nature');
 
return view('unsplash.search', compact('photos'));
}
}

Blade View:

@extends('layouts.app')
 
@section('content')
<h1>Search Results for Collections: "{{ $query }}"</h1>
@foreach ($collections['results'] as $collection)
<div>
<h2>{{ $collection['title'] }}</h2>
<p>{{ $collection['description'] ?? 'No description' }}</p>
<a href="{{ route('collections.photos', $collection['id']) }}">View Photos</a>
@endforeach
@endsection
</div>

Rate Limiting Middleware

This package includes middleware to monitor and handle the Unsplash API rate limits. The middleware is enabled by default and can be customized in the configuration options.

Configuration

The rate limiting settings are located in config/unsplash.php:

'rate_limiting' => [
'enabled' => env('UNSPLASH_RATE_LIMITING_ENABLED', true),
'threshold' => env('UNSPLASH_RATE_LIMITING_THRESHOLD', 10),
],
  • enabled: Enables or disables the rate limiting middleware.
  • threshold: The threshold for remaining requests at which the middleware intervenes.

Usage

To use the middleware in your routes, add it as follows:

Route::middleware(['unsplash.rate_limit'])->group(function () {
Route::get('/unsplash/search', [UnsplashController::class, 'search'])->name('unsplash.search');
// Other routes...
});

Error Handling

It's important to handle errors during API calls, especially when communicating with external services.

public function search(Request $request)
{
try {
$photos = Unsplash::searchPhotos('Nature');
} catch (\Exception $e) {
// Log the error or display a user-friendly message
return back()->withErrors('There was a problem communicating with the Unsplash API.');
}
 
return view('unsplash.search', compact('photos'));
}

Notes on the Unsplash API

  • Rate Limits: The Unsplash API has rate limits. Be sure to monitor the number of requests and use the provided middleware.
  • Attribution: When using photos, you must credit the photographers according to Unsplash's guidelines.
  • API Documentation: For more details, refer to the Unsplash API Documentation.

License

This package is released under the MIT License.

xchimx photo

My name is Tobias Schottstädt a full-stack web developer. My main focus is on application development, based on PHP and Javascript, frameworks Laravel and Vue.

Cube

Laravel Newsletter

Join 40k+ other developers and never miss out on new tips, tutorials, and more.


Xchimx Laravel Unsplash Related Articles

Integrate Unsplash in Your Laravel Application image

Integrate Unsplash in Your Laravel Application

Read article
The Certification of Competence for Laravel logo

The Certification of Competence for Laravel

A community-driven, proctored assessment across 4 levels designed to validate real-world Laravel knowledge, from Junior to mastery-level Artisan. Official Vue.js, Official Nuxt, Angular, React, JS certifications also available.

The Certification of Competence for Laravel
Harpoon: Next generation time tracking and invoicing logo

Harpoon: Next generation time tracking and invoicing

The next generation time-tracking and billing software that helps your agency plan and forecast a profitable future.

Harpoon: Next generation time tracking and invoicing
Lucky Media logo

Lucky Media

Get Lucky Now - the ideal choice for Laravel Development, with over a decade of experience!

Lucky Media
No Compromises logo

No Compromises

Joel and Aaron, the two seasoned devs from the No Compromises podcast, are now available to hire for your Laravel project. ⬧ Flat rate of $9500/mo. ⬧ No lengthy sales process. ⬧ No contracts. ⬧ 100% money back guarantee.

No Compromises
Statamic logo

Statamic

The drop-in ready Laravel CMS you’re been waiting for. Go full-stack or headless, flat file or database – it’s up to you.

Statamic
Blastup logo

Blastup

Blastup provides social media enhancement services including buying Instagram likes, followers, and views, with features like instant delivery and a variety of packages to suit different needs.

Blastup