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

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.

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.

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>

ErrorException Undefined variable

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

Send activation code after registration

this is my simple registration. I want to send an email to the user's after submitting button in this registration form.How can i do that??Thanx in advance.
1. In the view i have made an simple registration form as u can see i have added some basic information.
2.In my controller i have added validations. And save them in database.
4.And model has simple insert query.
form_view.php
<table>
<tr>
<td>Name</td><td><?php echo form_input($name);?></td>
<td><?php echo form_error('name');?></td>
</tr>
<tr>
<td>Email</td><td><?php echo form_input($email);?></td>
<td><?php echo form_error('email');?></td>
</tr>
<tr>
<td>Phone</td><td><?php echo form_input($phone);?></td>
<td><?php echo form_error('phone');?></td>
</tr>
<tr>
<td>Address</td><td><?php echo form_input($address);?></td>
<td><?php echo form_error('address');?></td>
</tr>
<tr>
<td>Division</td><td><?php echo form_dropdown('division',$division,'Please Select');?></td>
</tr>
<td></td><td><?php echo form_submit($submit);?></td>
</tr>
</table>
main.php
<?php
class main extends CI_Controller{
public function viewForm(){
$this->load->view('form_view');
}
public function insertData(){
$this->load->library('form_validation');
$this->form_validation->set_rules('name', 'Full Name', 'required|min_length[5]|max_length[12]|is_unique[address.name]');
$this->form_validation->set_rules('phone', 'Contact field', 'required|min_length[5]|max_length[12]|is_unique[address.phone]');
$this->form_validation->set_rules('address', 'Full Address', 'required|min_length[5]|max_length[12]|is_unique[address.address]');
$this->form_validation->set_rules('email', 'Email Address', 'required|min_length[5]|max_length[12]|is_unique[address.email]');
if($this->form_validation->run()==FALSE){
$this->load->view('form_view');
}else{
$sql="Select MAX(id) from address";// Auto Increment
$query= mysql_query($sql);
$selectid= mysql_fetch_array($query);
$finalid=$selectid[0]+1;
$data=array();
$data['id']=$finalid;
$data=array();
$data['name']=$this->input->post('std_name');
$data['phone']=$this->input->post('std_phone');
$data['address']=$this->input->post('std_address');
$data['division']=$this->input->post('division');
$data['email']=$this->input->post('email');
$this->load->model('main_model');
$this->main_model->save_user($data);
redirect('main/viewForm');
}
}
main_model.php
<?php
class main_model extends CI_Model{
public function save_user($data){
$this->db->insert('address',$data);
}
?>
}
?>
You might want to consider adding two columns on you user info table. Something like varchar activation_code & tinyint activated. On save user info generate activation code and send user a mail with that code within a link of your application url as well as save that code for that specific user with activated false value. On verify that code using that link change activated to true.
That will be my approach.
Before we start, I just want to point out that you should not have queries in your controller. That part must be in a model.
To send an email, you can use the codeigniter's library :
https://ellislab.com/codeigniter/user-guide/libraries/email.html
Here's how you can use it in your case :
if($this->form_validation->run()==FALSE)
{
$this->load->view('form_view');
}
else
{
$email = $this->input->post('email');
//Your stuff before the redirect
//If you have any particular smtp configuration (here, gmail)
$config = Array(
'protocol' => 'smtp',
'smtp_host' => 'smtp.gmail.com',
'smtp_user' => 'myemail#gmail.com',
'smtp_pass' => 'mypassword',
'smtp_port' => '465',
'charset' => 'utf-8',
'wordwrap' => TRUE
);
$this->load->library('email', $config);
$this->email->from('MyName#MySite.com', 'MyName');
$this->email->to($email);
$this->email->subject('Mail subject');
$msg = "Welcome to my website !";
$this->email->message($msg);
if($this->email->send())
{
//Stuff if mail succeded
}
else
{
//Stuff if mail failed
}
redirect('main/viewForm');
}