Reputation: 377
In my laravel project,I have an edit form and I want to set selected option based on database field. how should I do this?
I can't use $info variable inside php part in my view. I think this is because of controller part.
Here is my controller:
<?php
public function Edit()
{
$idNew = $_GET['id'];
$info = DB::table('test')->select('id','name','status')->where('id','=', $idNew)->get();
$returnHTML = view('layouts.edit',['info'=> $info])->render();
return response()->json([
'html'=> $returnHTML
]);
}
?>
And my view:
<html>
<option value="enabled" <?php if($info['status'] == 'enabled'){ echo ' selected="selected"'; } ?>>enabled</option>
</html>
Upvotes: 3
Views: 1761
Reputation: 4033
use data array and pass that with view
public function Edit()
{
$data=array();
$idNew = $_GET['id'];
$data['info'] = DB::table('test')->select('id','name','status')->where('id','=', $idNew)->get();
return view('layouts.edit')->with($data);
}
Upvotes: 0
Reputation: 4723
You are missing some parts.
$_GET
array. Use Request objectresponse()->json()
function, cause it is used for ajax calls.get()
function when you need one record. Use first()
function.Your controller should be:
use Illuminate\Http\Request;
public function Edit(Request $request)
{
$idNew = $request->input('id', 'default_value');
$info = DB::table('test')->select('id','name','status')->where('id','=', $idNew)->first();
return view('layouts.edit', ['info'=> $info]);
}
Your blade file should be:
<html>
<option value="enabled" {!! $info['status'] == 'enabled' ? "selected='selected'" : "" !!}>enabled</option>
</html>
Upvotes: 4