ErrorException Undefined variable - laravel-5.4

I have massage error like this ErrorException
Undefined variable: posts (View: C:\xampp\htdocs\TA\resources\views\petani\index.blade.php). how i to solve it ?
Controller :
public function index(){
$post = Desa::all();
return view('petani.index',compact ('desas'));
}
Route :
Route::get('petani', 'BiodataController#index');
Index :
<?php
$no = 1;
?>
#foreach ($posts as $post)
<td>{{$no++}}</td>
<td>{{$post->nama}}</td>
<td>
<button type="button" class="btn"><a href="{{ URL::to('coba/test/'.$post->id.'/edit') }}" >Edit</a></button>
{{ Form::open(['url' => 'coba/test/'.$post->id, 'method' => 'DELETE']) }}
{{ Form::button('delete', ['type' => 'submit', 'class' => 'btn']) }}
{{ Form::close() }}
</td>
</tr>
#endforeach

instead of compact('desas'), type ['posts' => $post] and you're good to go

Related

HOW TO PAGINATE A DATA FROM API

I was able to fetch certain data before but when I tried to add more code for pagination. It doesnt work anymore.
I need to paginate the data from API
error: "Trying to get property 'name' of non-object."
This is the result if I
if I dd($response) the results are:
{#274 ▼
+"pagelen": 10
+"next": "https://bitbucket.org/!api/2.0/repositories/spycetek?page=2"
+"values": array:10 [▶]
+"page": 1
+"size": 59
}
// I should paginate this. Here is my code for the controller.
public function index(Request $request, $page = 1)
{
$request = $this->client->get("https://bitbucket.org/!api/2.0/repositories/{$this->username}?page=" . $page,
[
'headers' => ['Authorization' => 'Bearer ' . $this->token]
]);
$response = json_decode($request->getBody()->getContents());
$repositories = $response->values;
$pagination = $response->pagelen;
$has_next_page = $pagination['has_next_page'];
$current_page = $pagination['page'];
$has_previous_page = $pagination['previous'];
$next_page = $pagination['next'];
return view('bitbuckets.repository')->with(compact('repositories'),
[ 'has_next_page' => $has_next_page,
'current_page' => $current_page, 'has_previous_page' => $has_previous_page,
'next_page' => $next_page]);
}
**//this is my blade.php file**
#extends('layoutss.layout')
#section('content')
<div class="container">
<div class="row" id="load" style="position: relative;">
<table class="table table-hover">
<thead>
<tr>
<th scope="col" class="text-secondary">Repositories</th>
</tr>
</thead>
<tbody>
#foreach($repositories as $key => $repository)
<tr>
<td>
{{$repository->name }}
</td>
</tr>
#if(isset($current_page))
<?php
$prev = $current_page - 1;
?>
#if(($has_next_page == true) && ($has_previous_page == false))
<li>Next</li>
#elseif(($has_next_page == false) && ($has_previous_page == true))
<li>Previous</li>
#elseif(($has_next_page == true) && ($has_previous_page == true))
<li>Previous</li>
<li>Next</li>
#endif
#endif
{{$repositories->links()}}
#endforeach
</tbody>
</table>
</div>
</div>
#endsection
and this is my code for routes.
Route::get('/{page?}', 'bb#index');
what is wrong with my codes
I messed up when it comes to pagination.
in blade.php was trying to display the list of all repositories and I wanted to paginate them. But I couldn't because of the error.

Call to undefined method App\Student::contains() in laravel

In my blade view, it is giving me an error Call to undefined method App\Student:: contains()
my controller
if($auth->user()->getRoleNames() == '["Parent"]'){
$id = $auth->user()->Parents_id;
$parent = ParentName::find($id);
$student = $parent->students;
$announce = AnnounceMent::get();
$roletype='parent';
return view('announcement.index',compact('student','roletype','announce'));
}
my view file
#foreach($announce as $ann)
#if($student->contains('id', $ann->student_id))
<tr>
<td>{{$i}}</td>
<td>{{$ann->announcement_type}}</td>
<td>
<?php $course = \App\Course::find($ann->course_id) ?>
{{$course->course_name}}
</td>
<td>
<?php $student = \App\Student::find($ann->student_id) ?>
{{$student['firstname'].' '.$student['lastname']}}
</td>
<td>{{$ann->description}}</td>
<td>
<a class="btn btn-success" href='{{ url("viewannounce/{$ann->id}") }}'>View</a>
</td>
</tr>
#endif
#php($i++)
#endforeach
this is my collection I am getting dd($students)
Collection {#595 ▼
#items: array:3 [▼
0 => Student {#596 }
1 => Student {#597 }
2 => Student {#598 }
]
}
contains is a collection method, you are calling it with a non-collection, if it will be App\Student::all()->contains('something') it will work fine, but App\Student::find(1)->contains('something') or App\Student::contains('something') will not work
Tinker results
>>> App\User::find(1)->contains('email')
BadMethodCallException with message 'Call to undefined method App/User::contains()'
>>> App\User::all()->contains('email')
=> false
>>> App\User::contains('email')
BadMethodCallException with message 'Call to undefined method App/User::contains()'
>>>
You can do
$student->id == $ann->student_id
in your situation, I guess.

How can Decode Json data in relational table laravel 5.8

I have a table Pemeliharaan with a column pertanyaan. In this column, I have data json like this ://
I update my question, this is dd not showing array on relational table user and alat. How? I need declare again in my controller? I update again, now I can show the data json. How can I parse it?
Pemeliharaan {#274 ▼
#table: "pemeliharaan"
#connection: "mysql"
#primaryKey: "id"
#keyType: "int"
+incrementing: true
#with: []
#withCount: []
#perPage: 15
+exists: true
+wasRecentlyCreated: false
#attributes: array:9 [▼
"id" => 42
"user_id" => 2
"alat_id" => 1
"pertanyaan" => array:8 [▼
"question1" => "Periksa kondisi kelistrikan dan kabel"
"answer1" => "false"
"question2" => "Periksa kondisi kabel dan tempat sambungan"
"answer2" => "false"
"question3" => "Periksa kondisi pencetakan (tinta dan kertas printer)"
"answer3" => "false"
"question4" => "Fix and squish bugs"
"answer4" => "false"
]
"catatan" => "22-11-1996"
"status" => "Harian"
"deleted_at" => null
"created_at" => "2019-03-28 15:41:44"
"updated_at" => "2019-03-28 15:41:44"
]
#original: array:9 [▶]
This data is question and answer. And I have a view like this. I have a function show and showQuestion.
And view like this
//View // no problem on here
<div class="box-body table-responsive no-padding">
<table class="table table-hover">
<tbody><tr>
<th>No</th>
<th>Nama Alat</th>
<th>Waktu</th>
<th>User Input</th>
<th>Action</th>
<th>Tanggal</th>
</tr>
#php
$no=0;
#endphp
#foreach ($pemeliharaan as $i)
<tr>
<td>{{ ++$no }} </td>
<td>{{ $i->alat->nama_alat}}</td>
<td>{{ $i->status}}</td>
<td>{{ $i->user->name}}</td>
<td> Lihat Data</span> </td>//in here redirect to showQuestion
<td>{{ $i->created_at}}</td>
</tr>
#endforeach
</tbody></table>
</div>
viewQuestion (if I click the button on the table will view this data)
#if( !is_null($pemeliharaan) )
<p> Laporan : {{ $pemeliharaan->status }} </p>
<p> Tanggal : {{ $pemeliharaan->created_at }} </p>
<p> Jenis Alat : {{ $pemeliharaan->alat->nama_alat }} </p>
<p> User : {{ $pemeliharaan->user->name }} </p>
<p> pertanyaan : {{ $pemeliharaan['question1'] }} </p>// now showing anything
#endif
#foreach(json_decode($pemeliharaan, true) as $value)
pertanyaan : {{ $value->pertanyaan['question1'] }}
#endforeach //corect me at here
//this is I want to decode this json but i dont
know what i do haha :(
this view (without question and answer) is don't have an error.
this is my controller :
public function show()
{
$pemeliharaan = Pemeliharaan::with(['user','alat'])->get();
return view('users.view',['pemeliharaan' => $pemeliharaan]);
}
public function showQuestion($id)
{
$pemeliharaan = Pemeliharaan::find($id);
$pemeliharaan->pertanyaan = json_decode($pemeliharaan->pertanyaan,true);
return view('users.view_question',compact('pemeliharaan'));
}
Having error like this
Undefined index: alat (View: /var/www/html/new/resources/views/users/view_question.blade.php)
I don't know how to decode and how to view in blade
You need to decode the specific column, not the whole object, try:
public function showQuestion($id)
{
$pemeliharaan = Pemeliharaan::find($id);
$pemeliharaan->pertanyaan = json_decode($pemeliharaan->pertanyaan,true);
return view('users.view_question',compact('pemeliharaan'));
}
And check in the viewQuestion if $pemeliharaan is null or not :
#if( !is_null($pemeliharaan) )
<p> Laporan : {{$pemeliharaan['status']}} </p>
<p> Tanggal : {{ $pemeliharaan['created_at'] }} </p>
<p> Jenis Alat : {{ $pemeliharaan->alat->nama_alat }} </p>
<p> User : {{ $pemeliharaan->user->name}} </p>
<p> pertanyaan : {{ $pemeliharaan['question1'] }} </p>
#endif
To parse all the Questions/Answers try :
#foreach($pemeliharaan->pertanyaan as $key => $value)
pertanyaan : {{ $key . ' - ' . $value}}
#endforeach
Play with this as you want.
you can use the json mutator to cast the field in a json directly :
https://laravel.com/docs/5.8/eloquent-mutators#array-and-json-casting
protected $casts = [
'pertanyaan' => 'json',
];
Then if you want to display it, I advice you this following :
create a blade file components/json.blade.php :
#if (!is_string($value))
#foreach($value as $key => $value)
<span class="ml-3"><strong>{{ ucfirst($key) }}</strong> : #include('components.json')</span>
#endforeach
#else
{{ $value }}
#endif
Then in your main file :
#include('components.json', ['value' => $pemeliharaan->pertanyaan])
(I have no idea of what pemeliharaan AND pertanyaan means, so maybe it's mess up, but you should pass your json converted to array as a value
The result will be a recursive list of all your json data presented that way :
Question1 : Periksa kondisi kelistrikan dan kabel
Answer1 : false
Question2 : Periksa kondisi kabel dan tempat sambungan
Answer2 : false

CakePHP 3.x update multiple rows

I have a table AssetsAssignations, with hundreds of rows. In some cases, the user needs to select many rows with a checkbox, and change the "status" for all of them together.
In my controller, I have this function
public function editMultiple()
{
$assetStatuses = $this->AssetsAssignations->AssetStatuses->find('list');
$this->paginate = [
'contain' => ['Assets', 'AssetStatuses', 'Clients', 'Rooms'],
'sortWhitelist' => [
'Assets.model_number',
'Assets.serial_number',
'AssetStatuses.name',
'Clients.last_name',
'Rooms.name',
]
];
$assetsAssignations = $this->request->data;
$assetsAssignations_ids = array();
foreach($assetsAssignations as $a){
$assetsAssignations_ids[$a['id']] = $a['id'];
$this->AssetsAssignations->updateAll(
array('AssetAssignation.id' => $assetsAssignations_ids)
);
$this->Session->setFlash(__('Statsus is updated for the selcted entries!'));
}
debug($assetsAssignations);
$query = $this->AssetsAssignations->find()
->contain(['Assets', 'AssetStatuses', 'Clients', 'Rooms']);
$filter = $this->Filter->prg($query);
$assetsAssignations = $this->paginate($filter, ['maxLimit' => 10000, 'limit' => 10000]);
$this->set(compact('assetsAssignations', 'assetStatuses'));
$this->set('_serialize', ['assetsAssignations']);
}
In my edit_multiple.ctp, I use a javascript to filter the data. And I put this code:
<table class="hoverTable dataTable">
<thead>
<tr>
<th>Select</th><th>Model Number</th><th>Serial Number</th><th>Room</th><th>Client</th><th>Status</th>
</tr>
</thead>
</thead>
<?php foreach ($assetsAssignations as $assetsAssignation): ?>
<tr>
<td><input name="data[AssetsAssignations][id][]" value="<?= $assetsAssignation->id ?>" id="AssetsAssignationsId1" type="checkbox"></td>
<td><?= $assetsAssignation->has('asset') ? $assetsAssignation->asset->model_number : '' ?></td>
<td><?= $assetsAssignation->has('asset') ? $assetsAssignation->asset->serial_number : '' ?></td>
<td><?= $assetsAssignation->has('room') ? $assetsAssignation->room->name : '' ?></td>
<td><?= $assetsAssignation->has('client') ? $assetsAssignation->client->last_name . ', ' . $assetsAssignation->client->first_name: '' ?></td>
<td><?= $assetsAssignation->has('asset_status') ? $assetsAssignation->asset_status->name : '' ?></td>
</tr>
<?php endforeach; ?>
</table>
<legend><?= __('') ?></legend>
</div>
<?= $this->Form->create($assetsAssignation) ?>
<fieldset>
<div class="row">
<div class="col-xs-3"><?= $this->Form->input('asset_status_id', ['options' => $assetStatuses, 'empty' => true, 'label' => __('Change Status To')]) ?></div>
</div>
</fieldset>
<?= $this->Form->button(__('Submit')) ?>
<?= $this->Form->end() ?>
When I debug the result, checking 3 entries, I get this:
[
'data' => [
'AssetsAssignations' => [
'id' => [
(int) 0 => '411',
(int) 1 => '413',
(int) 2 => '415'
]
]
],
'asset_status_id' => '3'
]
My question is: How to pass the selected row IDs to the "Submit" button after selecting the checkboxes ?
Thanks in advance.
I think that what you want to do is something like
if($this->request->is('post')
{
$ids = $this->request->data('data.AssetsAssignations.id');
$asset_status_id = $this->request->data('asset_status_id');
$this->AssetsAssignations->updateAll(
['asset_status_id ' => $asset_status_id ]
['id IN' => $ids]
);
}
Based on what #Arilia suggested, tis worked for me. In my controller, function, I put this:
$this->request->data;
$data = $this->request->data;
debug($data);
if($this->request->is(['patch', 'post', 'put']))
{
$ids = $this->request->data('data.AssetsAssignations.id');
$asset_status_id = $this->request->data('asset_status_id');
$this->AssetsAssignations->updateAll(
['asset_status_id ' => $asset_status_id ],
['id IN' => $ids]
);
}
In my view, I put this:
<td><input type="checkbox" name="data[AssetsAssignations][id][]" value="<?= $assetsAssignation->id ?>" id="ApplicationId1" ></td>

How to Add Select2 to row Dynamically in Yii2

I'm using Yii2 for my developments and I'm trying to Add Rows to table using plus button.
I'm able To add new row from that. And i need to append Krajee Select2 to my appending row. is that possible? how Can I Do that?
Following is my code use for append.
$('#main_tbl_body').append(
'<tr class='+row_class+' id="tbl_rw_appent_'+new_count+'">\n\
<td><a onclick ="removeMoreCommentField(this.id)" id="a_link_remove_'+new_count+'"><img id="image_remove_'+new_count+'" src="images/minus.png" style="width: 20px;height: 20px;cursor: pointer;" ></a></td>\n\
<td><div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">'+' <?php
//echo '<label class="control-label">Part Code</label>';
$data = ArrayHelper::map(Mproduct::find()
// where(['P_model' => $model->relatedToVehicle->V_model])
->all(), 'idProduct', 'P_description');
//$items = DealerHelper::getRemainItems();
echo Select2::widget([
'name' => 'part_description_1',
'data' => $data,
'options' => [
// 'class'=>'textBox mobviewmargin',
'placeholder' => 'Select Product',
// 'multiple' => true
],
'pluginOptions' => [
'closeOnSelect' => true,
'tags' => false,
'multiple' => false,
'allowClear' => false,
],
]);
?>'+'</div></td>\n\
<td></td>\n\ \n\\n\
<td></td>\n\ \n\\n\
<td></td>\n\ \n\
<td></td>\n\ \n\
<td><a onclick ="addMoreCommentField()" id="a_link_add_'+new_count+'"><img id="image_add_'+new_count+'" src="images/plus.png" style="width: 20px;height: 20px;cursor: pointer;" ></a></td>\n\
</tr>'
);
Please Help me