Undefined Variable in Blade Laravel - php

I have this in my controller:
public function detail($id) {
$data = DB::table('data_api')->where('id', $id)->get();
$carousel = DB::table('data_carousel')->where('data_api_id', $id)->get();
return view('detail', ['data_api' => $data]);
return view('detail', ['data_carousel' => $carousel]);
}
But when I try to echo-ing, $carousel by {{ $carousel }}, it says not found. But $data work perfectly. Any idea?
Undefined variable: carousel (View:
/mylaravelproject/resources/views/detail.blade.php)

you need to change the double return statement to a single return
return view('detail', ['data_api' => $data]);
return view('detail', ['data_carousel' => $carousel]);
to
return view('detail', ['data_api' => $data, 'data_carousel' => $carousel]);

you returning view two times that's why only $data_api is available in view,
try this
public function detail($id) {
$data = DB::table('data_api')->where('id', $id)->get();
$carousel = DB::table('data_carousel')->where('data_api_id', $id)->get();
return view('detail', ['data_api' => $data, 'data_carousel' => $carousel]);
}

Update:
public function detail($id) {
$data = DB::table('data_api')->where('id', $id)->get();
$carousel = DB::table('data_carousel')->where('data_api_id', $id)->get();
return view('detail', ['data_carousel' => $carousel,'data_api' => $data]);
}
You are returning two views from the same controller. After the first return execution of code is halt and it will not return the second view. That's why you are unable to get the second view parameters

You cannot return two times from a function and expect both to actually return something. After the first return, execution of the function is stopped.
Try returning both variables at once instead:
return view('detail', [
'data_api' => $api,
'data_carousel' => $carousel
]);

Replace your code with following:
public function detail($id) {
$data = DB::table('data_api')->where('id', $id)->get();
$carousel = DB::table('data_carousel')->where('data_api_id', $id)->get();
return view('detail')->with('data_api', $data)->with('data_carousel', $carousel);
}

You need to return view like below
public function detail($id) {
$data = DB::table('data_api')->where('id', $id)->get();
$carousel = DB::table('data_carousel')->where('data_api_id', $id)->get();
return view('detail', compact('data','carousel'));
}

is that really working now? You tell us you are getting
Undefined variable: carousel (View: /mylaravelproject/resources/views/detail.blade.php)
And you will get that because you are not passing the variable carousel to your view, you are naming your variables as data_api and data_carousell
Second, you should pass your variables as an asociative array in only one sentence not two view calls like this
return view('detail', ['carousel' => $carousel,'data' => $data]);

in my case i use
#if(isset($users))
before my foreach like this example:
<div class="form-group" id="boardAdminUserIdCon">
<p><span class="glyphicon glyphicon-briefcase" aria-hidden="true"></span> مدیر بورد</p>
<select name="boardAdminUserId" id="boardAdminUserId" class="form-control" required="required">
<option value="">{{ __('auth.CHOOSEYOURADMIN') }}...</option>
#if(isset($users))
#foreach($users as $user)
<option value="{{ $user['id'] }}">{{ $user["name"] }}
</option>
#endforeach
#endif
</select>
</div>

Related

Undefined variable issue Laravel 5.4

I've got stuck with this error so if ever pls forgive me because I'm still new at laravel. I got this error
Undefined variable: clientTransactions (View:
C:\xampp\htdocs\dcgwapo\resources\views\service_details\create.blade.php)
but I have a right code but I still wondering why it is still undefined variable given I define it in my controller.
create.blade.php in service details code
<div class="form-group">
<label for="client_transaction_id">Client Trans ID: </label>
<select class="form-control" name="client_transaction_id">
#foreach ($clientTransactions as $clientTransaction)
<option value= "{{ $clientTransaction->id }}">
{{ $clientTransaction->id }}
</option>
#endforeach
</select>
</div>
ServiceDetailsController code
public function create()
{
$users = User::pluck('fname', 'lname', 'id');
$services = Service::pluck('name', 'id');
$clientTransactions = ClientTransaction::all();
return view('service_details.create', ['users' => User::all()], ['services' => Service::all()], ['clientTransactions' => ClientTransaction::all()]);
}
ServiceDetail.php model code
public function clientTransaction()
{
return $this->belongsTo(ClientTransaction::class);
}
I hope you can help me. Thanks!
You're sending variables to your view the wrong way. The seconds argument should be an array with all your variables. As of now your adding a new parameter to the view function for each variable.
view('view', [...], [...], [...])
It should be like this:
view('view', [...1, ...2, ...3])
So what you need to change is the return statement to this:
return view('service_details.create', ['users' => User::all(), 'services' => Service::all(), 'clientTransactions' => ClientTransaction::all()]);
Second parameter to view function accepts an associative array of data, you are passing an indexedArray of arrays, Just use this return statement and you are good to go. ;)
return view('service_details.create', [
'users' => User::all(),
'services' => Service::all(),
'clientTransactions' => ClientTransaction::all()
]);
You can use compact to pass data from controller to view:
public function create()
{
$users = User::pluck('fname', 'lname', 'id');
$services = Service::pluck('name', 'id');
$clientTransactions = ClientTransaction::all();
return view('service_details.create',compact('users','services','clientTransactions');
}

Laravel- redirect with variable and display it in the view file

I have a controller
public function store(Request $request)
{if ($request->input('asc')){
$image = PropertyUser::where('user_id', '=', Auth::user()->id)->get();
foreach($image as $property)
{
$id = $property->property_id;
}
$image_ = Image::where('property_id', $id)->sortBy('description')->get();
return redirect('settings/photos');
How can i redirect with the $image_ variable and display it in my view file
#foreach ($image_ as $images)
<div class="image-warp"><img src="{{$images->filename}}"
style="width:100px;height:100px;"><br/><span style="color: #1b1e21">{{$images->description}}</span>
</div>
#endforeach
You can use the compact function to pass it to your view and reference it by the name.
return redirect('folder.name', compact('variableName');
return redirect()->route('folder.name', [$image]);
You can also send variable using below syntax also
return view('viewfile')->with('card',$card)->with('another',$another);
You can send data using redirect method. Those data will store inside Session Class.
return redirect('url')->with('message',$message);
like below
Session::get('variableName');
Session::get('message');
You should try this:
public function store(Request $request)
{if ($request->input('asc')){
$image = PropertyUser::where('user_id', '=', Auth::user()->id)->get();
foreach($image as $property)
{
$id = $property->property_id;
}
$image_ = Image::where('property_id', $id)->sortBy('description')->get();
return view('yourfolder.yourviewfile',compact('image_'));
Updated Answer
use Redirect;
public function store(Request $request)
{if ($request->input('asc')){
$image = PropertyUser::where('user_id', '=', Auth::user()->id)->get();
foreach($image as $property)
{
$id = $property->property_id;
}
$image_ = Image::where('property_id', $id)->sortBy('description')->get();
Redirect::to('settings/photos?image_='. $image_);
you can try with below code
return view('settings/photos')->with(['image' => $image_]);
Send an array of variables to your view:
return view('folder.viewfile', array(
'image_' => $image_,
'someother_variable' => $somevar,
));
Why you're using variable like this $image_ , you can use it simply like this $image or $whatEver
return view('folder.viewfile', compact('image'));
And now you can use this variable on view file as $image.
Do that in your controller function:
$request->session()->flash('order_id', $order_id);
And in view simply:
{{Session::get('order_id')}}
i just found myself in the same proble and solve with the help of you guys :)
on a complet example mi code ended like this:
mi FormCreate.php view recive an id from the previus page , so the url with out mask is "FormumariosCreate/16" in this example where the id is = 16 :
form:
<form method="post" action="{{ route('FormulariosStore2', $Formularios->idFormularios ) }}"> // is importan add the id on the rute
#csrf
<input type="text" name="textoPregunta" required="required" />
<button href="" class="btn btn-primary pull-right">Crear Nueva Pregunta</button>
</form>
rute in web.php:
Route::get('/FormulariosStore2/{idFormularios}', 'HomeController#FormulariosStore2')->name('FormulariosStore2');
Route::post('/FormulariosStore2/{idFormularios}', 'HomeController#FormulariosStore2')->name('FormulariosStore2');
and controler:
public function FormulariosStore2(Request $request,$id )
{
$validatedData = $request->validate([
'textoPregunta' => 'required|max:255',
]);
$ProyectoPreguntasF=ProyectoPreguntas::create($validatedData);
$Formularios = Formularios::findOrFail($id);
return redirect()->route('FormulariosCreate', $Formularios)->with('success','la operacion fue correcta.');
}
then it redirect to the rute "FormulariosCreate" with the id as a normal link with the id ,i hope it can add some content to the answer

How to solve the "Undefined variable" error in Laravel?

I am using Laravel, and I got an error:
Undefined variable: getFormTest (View: C:\xampp\htdocs\survey\resources\views\tambahformtest.blade.php)
That error references to this view:
<input value="{{ $getFormTest[0]->ms_test }}">
I have put $getFormTest in my controller:
public function TambahFormTest()
{
$ms_id = FormTest::max('ms_id');
$getFormTest = FormTest::Select('ms_test')->where('ms_id', '=', $ms_id)->get();
return view('tambahformtest', $getFormTest);
}
When returning a view in laravel, you have to pass an array of params.
return view ('myView', ['param1' => $v1, 'param2', $v2]);
then in your view
#if(isset($param1)
{{ $params->property }}
#endif
You should take a use of compact method of php
public function TambahFormTest()
{
$ms_id = FormTest::max('ms_id');
$getFormTest = FormTest::Select('ms_test')->where('ms_id', '=', $ms_id)->get();
return view('tambahformtest', compact('getFormTest'));
}
This would be sent to view as - ['getFormTest' => $getFormTest]
Hope this helps

Passing data from controller to view in Laravel

I am new to Laravel and I have been trying to store all records of table 'student' to a variable and then pass that variable to a view so that I can display them.
I have a controller - ProfileController and inside that a function:
public function showstudents() {
$students = DB::table('student')->get();
return View::make("user/regprofile")->with('students',$students);
}
In my view, I have this code:
<html>
<head>
//---HTML Head Part
</head>
<body>
Hi {{ Auth::user()->fullname }}
#foreach ($students as $student)
{{ $student->name }}
#endforeach
#stop
</body>
</html>
I am receiving this error: Undefined variable: students (View:regprofile.blade.php)
Can you give this a try,
return View::make("user/regprofile", compact('students')); OR
return View::make("user/regprofile")->with(array('students'=>$students));
While, you can set multiple variables something like this,
$instructors="";
$instituitions="";
$compactData=array('students', 'instructors', 'instituitions');
$data=array('students'=>$students, 'instructors'=>$instructors, 'instituitions'=>$instituitions);
return View::make("user/regprofile", compact($compactData));
return View::make("user/regprofile")->with($data);
For Passing a single variable to view.
Inside Your controller create a method like:
function sleep()
{
return view('welcome')->with('title','My App');
}
In Your route
Route::get('/sleep', 'TestController#sleep');
In Your View Welcome.blade.php. You can echo your variable like {{ $title }}
For An Array(multiple values) change,sleep method to :
function sleep()
{
$data = array(
'title'=>'My App',
'Description'=>'This is New Application',
'author'=>'foo'
);
return view('welcome')->with($data);
}
You can access you variable like {{ $author }}.
The best and easy way to pass single or multiple variables to view from controller is to use compact() method.
For passing single variable to view,
return view("user/regprofile",compact('students'));
For passing multiple variable to view,
return view("user/regprofile",compact('students','teachers','others'));
And in view, you can easily loop through the variable,
#foreach($students as $student)
{{$student}}
#endforeach
You can try this as well:
public function showstudents(){
$students = DB::table('student')->get();
return view("user/regprofile", ['students'=>$students]);
}
Also, use this variable in your view.blade file to get students name and other columns:
{{$students['name']}}
Try with this code:
return View::make('user/regprofile', array
(
'students' => $students
)
);
Or if you want to pass more variables into view:
return View::make('user/regprofile', array
(
'students' => $students,
'variable_1' => $variable_1,
'variable_2' => $variable_2
)
);
In Laravel 5.6:
$variable = model_name::find($id);
return view('view')->with ('variable',$variable);
public function showstudents() {
$students = DB::table('student')->get();
return (View::make("user/regprofile", compact('student')));
}
try with this code :
Controller:
-----------------------------
$fromdate=date('Y-m-d',strtotime(Input::get('fromdate')));
$todate=date('Y-m-d',strtotime(Input::get('todate')));
$datas=array('fromdate'=>"From Date :".date('d-m-Y',strtotime($fromdate)), 'todate'=>"To
return view('inventoryreport/inventoryreportview', compact('datas'));
View Page :
#foreach($datas as $student)
{{$student}}
#endforeach
[Link here]
$books[] = [
'title' => 'Mytitle',
'author' => 'MyAuthor,
];
//pass data to other view
return view('myView.blade.php')->with('books');
or
return view('myView.blade.php','books');
or
return view('myView.blade.php',compact('books'));
----------------------------------------------------
//to use this on myView.blade.php
<script>
myVariable = {!! json_encode($books) !!};
console.log(myVariable);
</script>
In laravel 8 and above, You can do route binding this way.
public function showstudents() {
$students = DB::table('student')->get();
return view("user/regprofile",['students'=>$students]);
}
In the view file, you can access it like below.
#foreach($students as $student)
{{$student->name}}
#endforeach

Passing arguments from route through view via controller doesn't work

I'm creating a Laravel 4 webapp and got the following route:
Route::get('products/{whateverId}', 'ProductController#index');
This is my index-function in ProductController:
public function index($whateverId)
{
$products = Product::all();
$data['whateverId'] = $whateverId;
return View::make('products', compact('products'), $data);
}
In my view, this returns the following error:
<p>Product: {{ $data['product'] }}</p>
ErrorException
Undefined variable: data (View: /Users/myuser/webapp/app/views/products.blade.php)
return View::make('products', compact('products'), "data"=>$data);
(or compact('data'))
Try passing it as:
$data['whateverId'] = $whateverId;
$data['products'] = Product::all();;
return View::make('products', $data);
And you'll have acces to it as
{{ foreach($products as ...) }}
and
{{ $whateverId }}
Or you can
$products = Product::all();
$data['whateverId'] = $whateverId;
return View::make('products')
->with('products', $products)
->with('whateverId', $whateverId);

Categories