Variable not showing on blade template - php

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>

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.

Related

Laravel backpack edit form displaying checklist items with selected values from database

In my crud controller, There is one field called "roles (Multiple checklist)", While before saving the roles, I am converting array into string like 1,2,3 using implode.
Ex: CrudController
setUp() method
$options = [
'name' => 'roles',
'label' => 'Roles',
'type' => 'checklist',
'entity' => 'roles',
'attribute' => 'name',
'model' => "Backpack\PermissionManager\app\Models\Role",
];
$this->crud->addField($options);
In Store method,
public function store(StoreRequest $request)
{
$sel_roles = $request->input("roles");
$roles = !empty($sel_roles) ? implode(",",$sel_roles) : "";
$request->request->set("roles",$roles);
//dd($request);
return parent::storeCrud($request);
}
Edit Method looks like this,
public function edit($id) {
$this->crud->hasAccessOrFail('update');
// get the info for that entry
$this->data['entry']= $this->crud->getEntry($id);
$options = [
'name' => 'roles',
'label' => 'Roles',
'type' => 'checklist',
'entity' => 'roles',
'attribute' => 'name',
'model' => "Backpack\PermissionManager\app\Models\Role",
];
$this->crud->addField($options);
$this->data['crud'] = $this->crud;
$this->data['fields'] = $this->crud->getUpdateFields($id);
$this->data['id'] = $id;
return view('crud::edit', $this->data);
}
If am trying to access, Edit page, I am getting below error,
ErrorException in line 15:
Call to a member function pluck() on string (View: /var/www/html/app/vendor/backpack/crud/src/resources/views/fields/checklist.blade.php)
checklist.blade.php page looks like below
<div #include('crud::inc.field_wrapper_attributes') >
<label>{!! $field['label'] !!}</label>
<?php $entity_model = $crud->getModel(); ?>
<div class="row">
#foreach ($field['model']::all() as $connected_entity_entry)
<div class="col-sm-4">
<div class="checkbox">
<label>
<input type="checkbox"
name="{{ $field['name'] }}[]"
value="{{ $connected_entity_entry->id }}"
#if( ( old( $field["name"] ) && in_array($connected_entity_entry->id, old( $field["name"])) ) || (isset($field['value']) && in_array($connected_entity_entry->id, $field['value']->pluck('id', 'id')->toArray())))
checked = "checked"
#endif > {!! $connected_entity_entry->{$field['attribute']} !!}
</label>
</div>
</div>
#endforeach
</div>
{{-- HINT --}}
#if (isset($field['hint']))
<p class="help-block">{!! $field['hint'] !!}</p>
#endif
</div>
How do I display the roles with selected values in the edit page.
Thanks
After hours of debug and verified,
Send the edit values in the collection format,
$options = [
'name' => 'role_id',
'label' => 'Roles',
'type' => 'checklist',
'entity' => 'roles',
'attribute' => 'name',
'model' => "Backpack\PermissionManager\app\Models\Role",
"value" => collect([$edit_value_array])
];

Laravel : how to pass parameters to my view and display them in Form::text and Form::date?

I'm trying to make a view for editing fields.
In fact I have two problems :
1) I get my data from my db with my controller, that's work, and I try to pass it to my view, that doesn't work...
2) I want to display these data in Form::text and Form::date, that doesn't work...
What I've in my controller :
public function edit($id)
{
$data = DB::connection('my-db')
->table('my-table')
->where('id', '=', $id)
->select('field1', 'field2')
->first();
return view('my-view', compact('field1', 'field2'));
}
I don't even know if compact in return view works like this
What I've in my view :
<div class="col-md-6">
{!! Form::text(field1, "", ['id'=> 'idField', 'class' => 'form-control', 'placeholder' => 'Modify field']) !!}
</div>
<div class="col-md-2">
{!! Form::date(field2, "", ['id'=> 'datetimepicker', 'class' => 'form-control']) !!}
</div>
I hope it's understandable, and thanks for your future answers :)
public function edit($id)
{
$data = DB::connection('my-db')
->table('my-table')
->where('id', '=', $id)
->select('field1', 'field2')
->first();
$field1 = $data->field1; // intialize the $field1 variable
$field2 = $data->field2; // intialize the $field2 varialbe
return view('my-view', compact('field1', 'field2'));
}
You were missing the $ sign before the variable name
Change field1 to $field1
<div class="col-md-6">
{!! Form::text('field1', $field1, ['id'=> 'idField', 'class' => 'form-control', 'placeholder' => 'Modify field']) !!}
</div>
<div class="col-md-2">
{!! Form::date('field2', $field2, ['id'=> 'datetimepicker', 'class' => 'form-control']) !!}
</div>
For more information, you can visit Laravel Form Collective Documentation

Custom Error Messages after submitting data Laravel

I already asked this question but there are a few things different this time. Last time the problem was fixed pretty well so now i just need a hand to tell me how to change the code so it works properly.
The thing i have changed is that i have implemented a way to successfully lend more then one book at once. So now i have an array which works perfectly.
So this is my View imagine this code 3 times one for every book you want to lend:
<div class="form-group row">
<label for="serialnumber" class="col-md-4 col-form-label text-md-right">{{ __('Gerät 1 (serialnumber) :') }}</label>
<div class="col-md-6">
<input id="serialnumber" type="text" class="form-control{{ $errors->has('serialnumber') ? ' is-invalid' : '' }}" name="serialnumber[]" value="{{ old('serialnumber') }}" required #if (Session::has('autofocus')) autofocus #endif>
#if ($errors->any())
<div class="alert alert-danger">The book with this serialnumber is already lend by antoher person
<ul>
</ul>
</div>
#endif
</div>
</div>
This is my Controller Code now:
public function store(BookRequest $request)
{
//if( !Book::find($request->get('serialnumber'))->exists() ) {
$this->middleware('guest');
request()->validate([
'serialnumber' => 'required',
'ma_id' => 'required'
]);
$requestData = $request->all();
$data = [
[
'serialnumber' => $requestData['serialnumber'][0],
'comment' => $requestData['comment'],
'ma_id' => $requestData['ma_id'],
],
[
'serialnumber' => $requestData['serialnumber'][1],
'comment' => $requestData['comment'],
'ma_id' => $requestData['ma_id'],
],
[
'serialnumber' => $requestData['serialnumber'][2],
'comment' => $requestData['comment'],
'ma_id' => $requestData['ma_id'],
]
];
Book::insert($data);
return redirect()->route('borrow.index')
->with('success','Successfully lend the book');
}
And the last is my Request.php page:
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class BookRequest extends FormRequest
{
public function authorize()
{
return true;
}
public function rules()
{
return [
'serialnumber[0]' => 'required|unique:borrowed,serialnumber,null',
'serialnumber[1]' => 'required|unique:borrowed,serialnumber,null',
'serialnumber[2]' => 'required|unique:borrowed,serialnumber,null',
'ma_id' => 'required',
];
}
public function messages()
{
return [
'serialnumber' => 'Seems like you have added the same book more than once!',
];
}
}
And this is my error message which i got after i tried to lend a book which is already lend by another person. Before i implemented the array thing this code worked perfect. Another question that i have is how could i implement a way which shows an error message which says "Sorry but this book is currently not in our database please press the info button and get some administraive help" so that basically an error message appears when the book is not in our database we have a lot of books so it is possible that we forget to scan one. Every help is much appreciated!!
EDIT:
Forgot the error message
htmlspecialchars() expects parameter 1 to be string, array given
Change your view:
#if(!empty(old('serialnumber')))
#foreach(old('serialnumber') as $i=>$value)
<input id="serialnumber" type="text" class="form-control{{ $errors->has('serialnumber') ? ' is-invalid' : '' }}" name="serialnumber[]" value="{{ old('serialnumber.'.$i) }}" required #if (Session::has('autofocus')) autofocus #endif>
#endforeach
#endif
where $i is your array index
aslo you can modify your rules and message like:
public function rules(){
return [
'serialnumber.0' => 'required|unique:borrowed,serialnumber,null',
'serialnumber.1' => 'required|unique:borrowed,serialnumber,null',
'serialnumber.2' => 'required|unique:borrowed,serialnumber,null',
'ma_id' => 'required',
];
}
or
public function rules(){
return [
'serialnumber.*' => 'required|unique:borrowed,serialnumber,null',
'ma_id' => 'required',
];
}
and
public function messages()
{
return [
'serialnumber.*' => 'Seems like you have added the same book more than once!',
];
}

How do I save multiple objects to a JSON column in MySQL and Laravel

I am using Laravel 5.4 and I have a problem in that when I save out a group of checkboxes, it only saves one of them if I save it like this:
<label class="checkbox-inline"> {!! Form::checkbox('languages[name]', 'English') !!} English</label><br/>
<label class="checkbox-inline"> {!! Form::checkbox('languages[name]', 'French') !!} French</label><br/>
<label class="checkbox-inline"> {!! Form::checkbox('languages[name]', 'Spanish') !!} Spanish</label><br/>
But it gives me a workable format in that I can run searches on name. The output here is just the first one I checked but in this format:
{"name": "English"}
If I take out the array field name in the [].
<label class="checkbox-inline"> {!! Form::checkbox('languages[]', 'English') !!} English</label><br/>
<label class="checkbox-inline"> {!! Form::checkbox('languages[]', 'French') !!} French</label><br/>
<label class="checkbox-inline"> {!! Form::checkbox('languages[]', 'Spanish') !!} Spanish</label><br/>
It saves all the values but it doesnt give me a workable format for my searches etc. The output here is:
["English", "French"]
My function in Laravel is like this
public function store(Request $request)
{
$data = $request;
dd($data['languages']);
$resource = Resource::create([
'user_id' => auth()->id(),
'status_id' => $status,
'title' => $data['title'],
'languages' => $data['languages'],
]);
return redirect($resource->path());
}
The column in MySQL called 'languages' is a JSON type.
Now ideally, I would like to get something similar to {"name": "English"} but not just saving as one item but all of them.
Any suggestions?
You can do the following:
<label class="checkbox-inline"> {!! Form::checkbox('languages[][name]', 'English') !!} English</label><br/>
<label class="checkbox-inline"> {!! Form::checkbox('languages[][name]', 'French') !!} French</label><br/>
<label class="checkbox-inline"> {!! Form::checkbox('languages[][name]', 'Spanish') !!} Spanish</label><br/>
It will give you:
"languages" => array [
0 => array: [
"name" => "English"
],
1 => array: [
"name" => "French"
],
2 => array: [
"name" => "Spanish"
]
]

load data to the form by the ID to update in laravel 5.2

I'm trying to populate the data to edit form. Here's my model
public function EditBatch($id,$request){
$data= DB::table('in_batch')
->where('id', $id)
->update(array(
'id'=>$request->input('id'),
'file_name' => $request->input('file_name'),
'batch_type' => $request->input('batch_type'),
'activity_type' => $request->input('activity_type'),
'schedule_time' => $request->input('schedule_time'),
'predecessor' => $request->input('predecessor'),
'priority' => $request->input('priority'),
'batch_remark'=>$request->input('batch_remark'),
'approved_by' => Auth::user()->id,
'approved_on'=>date("Y-m-d H:i:s"),
));
return $data;
}
here's my controller
public function edit($id){
$obatch = new BatchType();
$batch_type = $obatch->GetBatchTypeDropDown();
$batch = new ManageBatch();
$batch->GetBatchById($id);
return view('batch.edit', array('batch'=>$batch,'batch_type'=>$batch_type));
}
here's my view
{!! Form::open (array('url' => array('batch/update',$batch->id), 'class' => 'form-horizontal', 'method' => 'post','id'=>'editbatch')) !!}
<div class="form-group">
{!! Form::label('batch_id', 'batch_id',array('class'=>'col-md-4 control-label')) !!}
<div class="col-md-6">
{!! Form::text('batch_id',$batch->id,array('class'=>'form-control','id'=>'batch_id')) !!}
</div>
</div>
{!! Form::close() !!}
when i trying to load the data to the view as above error is displaying
Undefined property: App\Models\Batch\ManageBatch::$id (View: C:\wamp\www\hutch-in-portal\resources\views\batch\edit.blade.php)
how to solve this ?
thankyou
well i found a solution and the mistake was in the controller method
public function edit($id)
{
$obatch = new BatchType();
$batch_type = $obatch->GetBatchTypeDropDown();
$ouser = new ManageBatchUser();
$batch_user = $ouser->GetUserDropDown();
$batch = new ManageBatch();
$batch_details=$batch->GetBatchById($id);
return view('batch.edit',array('batch_details'=>$batch_details[0],'batch_type'=>$batch_type,'batch_user'=>$batch_user));
}
since i'm passing a single row to the view . i must add the index [0] in return. finally it worked

Categories