Ad

Variable Not Showing On Blade Template

- 1 answer

I'm creating a CRUD with 2 models in a form: automations and rules. 1 automation has 1 rule. On the edit form, I need to show field both from automations and rules. This is my controller on edit method.

public function edit($id)
{

    $actions = array(
            1 => 'Enable',
            2 => 'Pause',
        );

    $fields = \DB::table('fields')
    ->whereNull('field1_id')
    ->lists('field_name', 'id');

    $schedules = \DB::table('schedules')
    ->lists('schedule_name', 'id');

    $rules = \DB::table('rules')
        ->where('automation_id', '=', $id)
        ->get();


    return view('automations.automations', [
        'automations' => Automations::find($id),
        'actions' => $actions,
        'fields' => $fields,
        'schedules' => $schedules,
        'rules' => $rules
    ]);

But on my form, I my not able to show the values from Rules, only for Automations. What I am doing wrong? This is the blade form for 1 field from Rules:

<div class="form-group">


    <label for="task-name" class="col-sm-3 control-label">Field 1 </label>
            <div class="col-sm-6">
                {!! 

                    Form::select(   
                        'field1', 
                        (['' => 'Select a Field'] + $fields), 
                        (isset($rules->field1) ? $rules->field1 : null),  
                        ['class' => 'form-control','id' => 'field1']
                    ) 


                !!}
            </div>
            </div>

And for 1 field from automations:

<div class="form-group">
            <label for="task-name" class="col-sm-3 control-label">Action on Campaigns</label>
            <div class="col-sm-6">
                {!! 

                    Form::select(   
                        'action_id', 
                        (['' => 'Select an Action'] + $actions), 
                        (isset($automations->action_id) ? $automations->action_id : null),  
                        ['class' => 'form-control']
                    ) 


                !!}
            </div>
            </div>
Ad

Answer

DB::get() returns an array of stdClass objects. Therefore, $rules is an array, so you can't just access properties like $rules->field1. You need to iterate the array to find the actual object you're looking for, and then check that object. Or, if there's actually only one record, you can use first() instead of get().

DB::find() returns stdClass object or null, depending on if the record was found. That is why your automations works.

Ad
source: stackoverflow.com
Ad