Haniye Shadman
Haniye Shadman

Reputation: 377

How can I set selected option based on database field in blade template?

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

Answers (2)

PHP Geek
PHP Geek

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

Giacomo M
Giacomo M

Reputation: 4723

You are missing some parts.

  1. In laravel controller do NOT use $_GET array. Use Request object
  2. In blade file do NOT use php tag, use blade syntax
  3. If you want to show a blade view from controller, do NOT use response()->json() function, cause it is used for ajax calls.
  4. Do NOT use 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

Related Questions