0

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?

6
  • 1
    You are not loading a view... Commented Oct 13, 2022 at 7:19
  • Maybe show your index() method that calls that view Commented Oct 13, 2022 at 7:19
  • return view('dashboard.index'); doesn't pass any data to the view. Make sure it does Commented Oct 13, 2022 at 7:31
  • return view('dashboard.index', [ 'yourData' => 'foo' ]); Commented Oct 13, 2022 at 7:36
  • 1
    Route::get('/dashboard/{uuid}', [DashboardController::class, 'index']); In route you have to pass 1 params uuid to have uuid in controller function public function index($uuid) Commented Oct 13, 2022 at 8:36

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.