Access User’s NFTs via MetaMask in Laravel
Step 1: Install the Metamask Ethereum provider
- In your Laravel application, open a terminal and navigate to the root directory.
- Install the MetaMask Ethereum provider by running the following command:
npm install --save ethers
Step 2: Add a route and controller method
- Open your routes file (usually
web.php
) and add a new route:
Route::get('/connect-wallet', 'WalletController@connect')->name('connect-wallet');
- Create a new controller or use an existing one (e.g.,
WalletController
) and add theconnect
method:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\Models\User;
use App\Services\MetaMaskService;
class WalletController extends Controller
{
public function connect(Request $request)
{
// Get the authenticated user
$user = Auth::user();
// Generate a unique token for this connection request
$token = bin2hex(random_bytes(16));
// Save the token in the user's session
$request->session()->put('connect_token', $token);
// Generate the MetaMask connection URL
$connectionUrl = MetaMaskService::generateConnectionUrl($token);
return view('connect-wallet', ['connectionUrl' => $connectionUrl]);
}
}
Step 3: Create the MetaMask service
- Create a new service file (e.g.,
MetaMaskService.php
) in theapp/Services
directory. - Add the following code to the
MetaMaskService
class:
<?php
namespace App\Services;
class MetaMaskService
{
public static function generateConnectionUrl($token)
{
// Replace this with your actual frontend URL where MetaMask will redirect after connecting
$redirectUrl = 'https://your-app.com/after-connect';
// Generate the MetaMask connection URL
$connectionUrl = "https://metamask.app.link/Dapp/your-app.com/connect-wallet?token={$token}&redirect={$redirectUrl}";
return $connectionUrl;
}
}
Step 4: Create the “Connect Wallet” view
- Create a new view file (e.g.,
connect-wallet.blade.php
) and add the following code:
<!-- Include the MetaMask JavaScript library -->
<script src="https://cdn.jsdelivr.net/npm/@metamask/detect-provider@1.2.0/dist/detect-provider.min.js"></script>
<script>
async function connectWallet() {
// Detect MetaMask provider
const provider = await detectEthereumProvider();
if (provider) {
// Request user authorization
const accounts = await provider.request({ method: 'eth_requestAccounts' });
if (accounts.length > 0) {
const walletAddress = accounts[0];
// Redirect to the page where you retrieve the user's NFTs
window.location.href = '{{ route('get-user-nfts') }}?walletAddress=' + walletAddress;
} else {
alert('No wallet address found.');
}
} else {
alert('MetaMask extension not detected. Please install MetaMask.');
}
}
</script>
<!-- Add a button to connect the wallet -->
<button onclick="connectWallet()">Connect Wallet</button>
Step 5: Add a route and controller method to retrieve NFTs
- Open your routes file (usually
web.php
) and add a new route:
Route::get('/user-nfts', 'NFTController@index')->name('get-user-nfts');
- Create a new controller or use an existing one (e.g.,
NFTController
) and add theindex
method:
use GuzzleHttp\Client;
class NFTController extends Controller
{
public function index()
{
// Get the authenticated user
$user = Auth::user();
// Make a request to the OpenSea API to fetch the user's NFTs
$nfts = $this->fetchUserNFTs($user->wallet_address);
return view('user-nfts', ['nfts' => $nfts]);
}
private function fetchUserNFTs($walletAddress)
{
// Create a Guzzle HTTP client instance
$client = new Client();
// Set the OpenSea API endpoint and wallet address
$endpoint = "https://api.opensea.io/api/v1/assets";
$query = [
'owner' => $walletAddress,
'order_direction' => 'desc',
'offset' => 0,
'limit' => 10, // Adjust the limit as per your requirements
];
// Send a GET request to the OpenSea API
$response = $client->get($endpoint, ['query' => $query]);
// Decode the response JSON
$data = json_decode($response->getBody(), true);
// Extract the relevant NFT data from the response
$nfts = [];
foreach ($data['assets'] as $asset) {
$nft = [
'name' => $asset['name'],
'image' => $asset['image_preview_url'],
// Include any other relevant NFT information you want to retrieve
];
$nfts[] = $nft;
}
return $nfts;
}
}
- Create a new view file (e.g.,
user-nfts.blade.php
) and display the user’s NFTs as desired.
<!-- user-nfts.blade.php -->
@extends('layouts.app')
@section('content')
<div class="container">
<h1>User NFTs</h1>
<div class="row">
@foreach ($nfts as $nft)
<div class="col-md-4">
<div class="card mb-4">
<img src="{{ $nft['image'] }}" class="card-img-top" alt="{{ $nft['name'] }}">
<div class="card-body">
<h5 class="card-title">{{ $nft['name'] }}</h5>
<!-- Display additional NFT information as needed -->
</div>
</div>
</div>
@endforeach
</div>
</div>
@endsection
That’s it! With these steps, you have a Laravel application with a “Connect Wallet” button that connects the user to MetaMask, retrieves the user’s wallet address, and redirects to a page where their NFTs can be fetched using the wallet address.
Read More Posts
1 thought on “To connect a Laravel application with MetaMask and retrieve a user’s NFTs”
Comments are closed.