0

I'm using laravel in my backend and react as my frontend. When I try to pass variables from my controller to the view with this:

public function index()      
{ 
  return view('welcome')->with('name', 'San Juan Vacation');
}

And want to retrieve it in my welcome blade file with this:

<p>{{ $name }}</p>

It doesn't work for some reason. It says undefined variable $name. Any idea what might solve this issue?

1
  • Just replace this part of code ->with(['name'=> 'San Juan Vacation']); Commented Apr 9, 2019 at 3:58

3 Answers 3

1

Pass variable Controller to view

public function index()      
{ 
   $name = 'San Juan Vacation';
   $color = 'red';
  // .....
  return view('welcome', compact('name', 'color'));
}

If you want to pass with, that time :

return view('welcome')->with(['name'=>$name,'color'=>$color]);

Write in welcome.blade.php

 <p>{{ $name }}</p>

I hope this work for your case.

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

Comments

0

To send data from a controller to the view use this code: (you were close)

public function index()      
{ 
  $name = 'San Juan Vacation';
  $color = 'red';
  // .....
  return View::make('welcome', compact('name', 'color'));
}

<p>{{ $name }}</p>

5 Comments

It still says not defined. Do I need to define it into a constructor when loading the page?
Are you sure the route is applying to the right controller? you can try also php artisan view:clear
@ShehbanPatel Do you have the route set like Route::get('/something', 'YourController@index')->name('something.index')
Thanks for that. Looks like my route was wrong which was causing these errors in the first place.
Cool, let me know if you still have some trouble!
0

Modify you code as below

public function index()      
{   
    $name = "San Juan Vacation";
    return view('welcome')->with(['name'=>$name]);
}

Note: Avoid passing hard coded value to blade file, set variable for each.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.