Home > database >  Can't pass a variable from controller to view - Laravel
Can't pass a variable from controller to view - Laravel

Time:10-23

I'm trying to pass a variable from controller to view but I got an 'Undefined variable' error.

web.php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\DashboardController;

Route::get('/dashboard', [DashboardController::class, 'index']);    
Route::get('/dashboard/{uuid}/download', [DashboardController::class, 'download'])->name('dashboard.download');

DashboardController.php

namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Licence;
use App\Models\Download;
use Auth;
    
public function index($uuid)
{
    if (Licence::where('user_id', Auth::id())->exists()) {
        $download = Download::where('uuid', $uuid)->firstOrFail();
        return view('dashboard.index', compact('download'));
    } else {
        return redirect('/checkout');
    }
}
        
public function download($uuid)
{
    $download = Download::where('uuid', $uuid)->firstOrFail();
    $pathToFile = storage_path('app/public/plugin.zip');
    return response()->download($pathToFile);
}

dashboard/index.blade.php

<a href="{{ route('dashboard.download', $download->uuid) }}">

Any idea?

CodePudding user response:

The index function in the DashboardController cannot find $uuid. You already declared and passed parameter $uuid to the index function in the DashboardController, but $uuid have not been defined. Change

Route::get('/dashboard', [DashboardController::class, 'index']);    

To

Route::get('/dashboard/{uuid}',[DashboardController::class, 'index']);

Notice: You have to pass uuid as a parameter to the '/dashboard' route so that the variable $uuid will be given a value(defined) through the url when a route is visited. Ensure that the all url of the index page in your project is also modified to accommodate the new parameter(uuid), else you will get a 404 error. When you visit

/dashboard/1

$uuid gets a value of 1, and so on.

  • Related