Retrieve data from laravel to blade - php

I'm a beginner in laravel and at uni our task was to retrieve data from a a file called pms.php which contains all the results for the prime minsters such as name, year and state. No matter what I do I cant get it to work.
This is my web.php file:
require(app_path().'/pms.php');
// To do: Display search form
Route::get('/', function()
{
return view('search_form');
});
// To do: Perform search and display results
Route::get('search', function()
{
//$name = request('name');
//$year = request('from', 'to');
//$state = request('state');
$pms = search('name','from','to','state');
return view('search')->with('name', $pms)
->with('from', $pms)->with('to', $pms)->with('state', $pms);
});
/* Functions for PM database example. */
/* Search sample data for $name or $year or $state from form. */
function search($name, $year, $state) {
$pms = getPms();
// Filter $pms by $name
if (!empty($name)) {
$results = array();
foreach ($pms as $pm) {
if (stripos($pm['name'], $name) !== FALSE) {
$results[] = $pm;
}
}
$pms = $results;
}
// Filter $pms by $year
if (!empty($year)) {
$results = array();
foreach ($pms as $pm) {
if (strpos($pm['from'], $year) !== FALSE ||
strpos($pm['to'], $year) !== FALSE) {
$results[] = $pm;
}
}
$pms = $results;
}
// Filter $pms by $state
if (!empty($state)) {
$results = array();
foreach ($pms as $pm) {
if (stripos($pm['state'], $state) !== FALSE) {
$results[] = $pm;
}
}
$pms = $results;
}
return $pms;
}
This is my search.blade.php file
#extends('layouts.master')
#section('title')
Query Search Result
#endsection
#section('content')
Search result for {{ $name }} {{ $year }} {{ $state }}
#endsection
This is my search_form.blade.php:
#extends('layouts.master')
#section('title')
Search Form
#endsection
#section('content')
<p>
<h2>Australian Prime Ministers</h2>
<h3>Query</h3>
<form method="get" action="search">
{{csrf_field()}}
<table>
<tr><td>Name: </td><td><input type="text" name="name"></td></tr>
<tr><td>Year: </td><td><input type="text" name="year"></td></tr>
<tr><td>State: </td><td><input type="text" name="state"></td></tr>
<tr><td colspan=2><input type="submit" value="Search">
<input type="reset" value="Reset"></td></tr>
<table>
</form>
</p>
#endsection
Do you guys know why it isn't working? The issue I'm facing right now is:
htmlspecialchars() expects parameter 1 to be string, array given (View: /home/ubuntu/workspace/Week4/assoc-laravel/resources/views/search.blade.php)

Send data in compact(),
return View::make('foo.bar')
->with(compact('test'));
OR
Recommended ->
return view('foo.bar', compact('your_php_variable'))

Related

increment doesn't apply at the first time

i'm newbie in laravel and i'm working on a shop website and i've got stuck in the cart part of the project.
and for that i'm using a pivot table with ManyToMeny relation
the main problem is when i add to the cart for the first time it gives me always one, but in the second time it increments the third time it increments too. i searched in the pivote table structure and i found 1 as a default value.
first add
result of the first add
second add
results of the second add it increments !
i don't know how to change the value of the given 1 in the first. I don't know what to change to make the first add value like the input value.
i think the expected outcome of this code is to increment the value of 0 with the value given by input number
this is my controller
$found = false;
$user = Auth::user();
$product = produit::find($id);
if (!$product || !$user) {
abort(404);
}
if($product->rupture_stock == true){
return redirect()->back()->with('error', 'Rupture de stock');
}
$panier = $user->panier;
foreach ($panier->produits as $pr) {
if ($pr->id == $id){
$found = true;
$qt = $pr->pivot->quantite;
$first_num = $request->get('quantite');
// $first_num = $_POST['quantite'];
$second_num = 0;
$result = '';
// $qt = $_POST['quantite'];
if (is_numeric($first_num) && is_numeric($second_num)) {
$result = $first_num + $second_num;
$qt += $result;
}
$panier->produits()->updateExistingPivot($pr->id, ['quantite' => $qt]);
}
}
if (!$found) {
$panier->produits()->attach($product->id);
}
this is my blade
<form action="{{ url('add/'.$prod->id) }}" method="post" style="margin-bottom:20px" class="cart" id="product_addtocart_form" enctype='multipart/form-data'>
#csrf
<input type="number" value="" name="quantite" class="text" step="1" min="1" max="11" size="4" placeholder="" inputmode="numeric" />
<button style="border-radius: 50px; /*padding:0 20px; margin-left:40px*/" type="submit" name="add-to-cart" value="352" class="single_add_to_cart_button button alt">Ajouter</button>
</form>
You can do it more simple by using syncWithoutDetaching:
$user = Auth::user();
$product = produit::find($id);
if (!$product || !$user) {
abort(404);
}
if($product->rupture_stock == true){
return redirect()->back()->with('error', 'Rupture de stock');
}
$panier = $user->panier;
$panier->produits()->syncWithoutDetaching([$id => ['quantite' => (int)request('quantite')]]);
https://laravel.com/docs/8.x/eloquent-relationships#syncing-associations

Laravel Product Filter by Price

I have a filter route to filter my products by brand & weight & count and taste and all are working fine but when i want to add a sort filter its not working, i want to sort it by pirce ( Ascending and descending).
here is my codes
Route:
Route::match(['get', 'post'], 'products/filter', [SearchController::class, 'filterall']);
SearchController:
public function filterall(Request $request){
$data = $request->all();
// echo "<pre>"; print_r($data);
$brandUrl = "";
$weightUrl = "";
$countUrl = "";
$tasteUrl = "";
$sortUrl = "";
if(!empty($data['brandFilter'])){
foreach ($data['brandFilter'] as $brand){
if(empty($brandUrl)){
$brandUrl = "&brand=".$brand;
}else{
$brandUrl .= "-".$brand;
}
}
}
if(!empty($data['weightFilter'])){
foreach ($data['weightFilter'] as $weight){
if(empty($weightUrl)){
$weightUrl = "&weight=".$weight;
}else{
$weightUrl .= "-".$weight;
}
}
}
if(!empty($data['countFilter'])){
foreach ($data['countFilter'] as $count){
if(empty($countUrl)){
$countUrl = "&count=".$count;
}else{
$countUrl .= "-".$count;
}
}
}
if(!empty($data['tasteFilter'])){
foreach ($data['tasteFilter'] as $taste){
if(empty($tasteUrl)){
$tasteUrl = "&taste=".$taste;
}else{
$tasteUrl .= "-".$taste;
}
}
}
if(!empty($data['sort'])){
foreach ($data['sort'] as $sort){
if(empty($sortUrl)){
$sortUrl = "&sort=".$sort;
}else{
$sortUrl .= "-".$sort;
}
}
}
$finalUrl = "category/".$data['url_id'].'/'.$data['url_slug']."?".$brandUrl.$weightUrl.$countUrl.$tasteUrl.$sortUrl;
return redirect::to($finalUrl);
}
*** My View Controller ***
public function allCategory(Request $request, $id){
$catt = DB::table('categories')->where('id', $id)->first();
$products = Product::where('category_id', $catt->id)->where('status', '1')
->orderBy('brand_id', 'ASC');
if(!empty($_GET['brand'])){
$brandArray = explode('-', $_GET['brand']);
$products = $products->whereIn('brand_id', $brandArray);
}
if(!empty($_GET['weight'])){
$weightArray = explode('-', $_GET['weight']);
$products = $products->whereIn('product_weight', $weightArray);
}
if(!empty($_GET['count'])){
$countArray = explode('-', $_GET['count']);
$products = $products->whereIn('product_count', $countArray);
}
if(!empty($_GET['taste'])){
$tasteArray = explode(',', $_GET['taste']);
foreach ($tasteArray as $taste){
$products = $products->where('product_taste','LIKE', "%$taste%");
}
if(!empty($_GET['sort'])){
$sortArray = explode('-', $_GET['sort']);
$products = $products->orderBy('selling_price', $sortArray);
}
}
$products = $products->paginate(12);
return view('pages.all_category', compact('products', 'catt'));
}
and this is the view code:
<div class="row" id="search-results">
<div class="col-lg-12 col-md-12">
<div class="toolbar toolbar-products">
<div class="toolbar-sorter sorter">
<label class="sorter-label" for="sort">Sort By</label>
#if(!empty($_GET['sort']))
<?php $sortArray = explode('-', $_GET['sort']) ?>
#endif
<select id="sort" name="sort[]" class="sorter-options" onchange="javascript:this.form.submit();">
<option value="">Select</option>
#if(!empty($_GET['sort']))
<?php $price = $_GET['sort'] ?>
#endif
<option value="ASC" #if(!empty($sortArray) && in_array('ASC', $sortArray)) selected="" #endif>Lowest Price</option>
<option value="DESC" #if(!empty($sortArray) && in_array('DESC', $sortArray)) selected="" #endif>Highest Price</option>
</select>
</div>
</div>
</div>
</div>
im doing this by Form in page.
I think orderBy in front Controller is not working is there other way to sort that?

how to update multiple value in codeigniter

I have input data that I will fill with different values, I do multiple updates
but I have an error which is:
Unknown column 'Array' in 'field list' UPDATE service SET
charges_order = WHERE array id_service = '1'
how to overcome this?
example img
View
<?php $no = 1; foreach ($invoice as $m) { ?>
<tbody id="tbody">
<form class="form-signin" method="post" action="<?php echo base_url();?>backend/report/update/<?php echo $m->id_service; ?>">
<tr class="deleted">
<td><input type="text" class="form-control" name="charges_order[]" value="<?php echo $m->charges_order;?>"></td>
</tr>
</form>
</tbody>
<div class="box-footer">
<button type="submit" class="btn bg-blue btns-flat margin">Simpan</button>
</div>
<?php } ?>
Controller
public function update($id_service)
{
foreach ($this->input->post('charges_order') as $data) {
$data = array(
'charges_order' => $this->input->post('charges_order')
);
// echo '<pre>', print_r($data);
$this->M_report->update($id_service, $data);
redirect('backend/report');
}
}
Model
public function update($id_service, $data)
{
$this->db->where('id_service', $id_service);
$this->db->update('service', $data);
}
Change your controller to this-
public function update($id_service){
$charges_order = json_encode($this->input->post('charges_order'));
$data = array(
'charges_order' => $charges_order
);
$this->M_report->update($id_service, $data);
redirect('backend/report');
}
This should work for you.
You are in a loop. You must use the variable.
$data = array(
'charges_order' => $data
);
You can convert array into a string and then update the table.
//example
[1,2,3,4] -> "1,2,3,4"
Here is the code
public function update($id_service)
{
$data = array(
'charges_order' => implode(",", $_POST['charges_order'])
);
// echo '<pre>', print_r($data);
$this->M_report->update($id_service, $data);
redirect('backend/report');
}
When you are retrieving, you can reverse the process
public function get_orders($id_service)
{
$this->db->select('charges_order');
$this->db->where('id_service', $id_service);
$result = $this->db->get('service')->result_array();
return explode(",", $result["charges_order"]); //returns an array
}

How to update database base on laravel checkbox value

I load check boxes from database with they are checked or not,
<div class="row">
<div class="col-xs-12">
<div class="form-group">
#php
$json = $orders->data;
$json = json_decode($json, true);
$products = $json['order_info']['products'];
$data = '';
foreach ($products as $hitsIndex => $hitsValue) {
$data .= $hitsValue['type']. ', ';
}
$data = rtrim($data, ', ');
$agosProducts = Utility::constant('agos_products1');
#endphp
{{Html::validation($orders, 'product')}}
<label for="products" class="control-label">{{Translator::transSmart('app.Products', 'Products')}}</label><br><br>
#foreach($agosProducts as $product)
<label class="control-label "for="{{ $product['type'] }}">
<input id="{{ $product['type'] }}" name="{{ $product['type'] }}" type="checkbox" value="{{ $product['type'] }}"
#foreach ($products as $hitsIndex => $hitsValue)
#if(in_array($hitsValue['type'], $product)) checked=checked #endif
#endforeach
>
{{ $product['name'] }}
</label>
<br>
#endforeach
</div>
</div>
</div>
Now i want to update my database base on checkbox value.
For example if say i load checkbox 1 as checked from database and now it's unchecked i need to update it in database.
This code i can get all the current status of checkbox but i don't know previous values of this. So it hard update statue of current values and add new status in database,
$chks = array('multicolor','resizable','showRuler','namesNumbersEnabled');
foreach ($chks as $chk) {
$product->setAttribute($chk, (Input::has($chk)) ? true : false);
}
This is my json object save in data column
{"user_token":"ad48c412-3866-4ac9-adf6-3328911ae46c",
"order_info":
{"order_id":"CGC12345678","company_id":32,"price":1000.5,"currency":"MYR",
"products":[
{"type":"HR_ECLAIM","name":"HREClaim","is_fixed_price":true,"price":500.5,"currency":"MYR"},
{"type":"HR_ELEAVE","name":"HRELeave","is_fixed_price":true,"price":500,"currency":"MYR"}
],
"total_invoices":200,"total_staffs":80},"url":"https://drive.google.com/open?id=1Is6QsnuMLu9ZIpqeEzR2O2Ve1wUyF92aVCg55kWsOgc"}
i load [order_info][products][type] as checked products in while i load all the products from env file. I only need to save checked check box products in db.
Can someone helps me?
This is the complete working solution i done for my question!
public function edit($id, $attributes){
$orders = (new Agos())->load($id);
$json = $orders->data;
$json = json_decode($json);
$checkedit= $attributes['check_list'];
if (is_array($checkedit) || is_object($checkedit))
{
foreach($checkedit as $chked1){
$exists = false;
foreach($json->products as $key => $val)
{
// update if products exists
if($val->type == $chked1) {
$val->status = 'true';
$exists = true;
}
if(array_key_exists('status', $val)) {}
else{ $val->status = 'false';}
}
if($chked1 == 'FIN_REPORTING')
{
$name = 'Finance reporting & book keeping';
}
elseif ($chked1 == 'FIN_ADVISORY')
{
$name = 'Finance Advisory';
}
elseif ($chked1 == 'PAYROLL_HRDB')
{
$name = 'PAYROLL_HRDB';
}
elseif ($chked1 == 'HR_ELEAVE')
{
$name = 'HR E-Leave';
}
else
{
$name = 'HR E-Claim';
}
//if products not exists add new products
if(!$exists) {
$newproduct = new \stdClass();
$newproduct->type = $chked1;
$newproduct->name = $name;
$newproduct->is_fixed_price = false;
$newproduct->currency = "MYR";
$newproduct->status = "true";
array_push($json->products, $newproduct);
}
}
}
//remove all products that have status = false
foreach($json->products as $index => $product) {
if ( $product->status == "false") {
unset($json->products[$index]);
}
}
$json->products = array_values($json->products);
json_encode($json, JSON_PRETTY_PRINT);
//remove status element from products
foreach($json->products as $index => $product) {
unset($product->status);
}
$json->products = array_values($json->products);
json_encode($json, JSON_PRETTY_PRINT);
$json->google_drive_url= $attributes['data'];
$json->remark= $attributes['remark'];
$json->status= $attributes['status'];
$json->total_invoices= $attributes['total_invoices'];
$json->total_staffs= $attributes['total_staffs'];
$json1 = json_encode($json);
$status = $attributes['status'];
$total_price = str_replace(',','', $attributes['total_price']);
DB::table('orders')
->where('id', $id)
->update(['data' => $json1,'status' => $status, 'price' => $total_price]);
}

Twitter Typeahead in CodeIgniter. Not passing array datum to hidden form field

I'm trying to use the typeahead.js Twitter Typeahead (not Bootstrap typeahead) to display names pulled from a mysql table using the CodeIgniter framework. The model also collects id values along with the name.
The controller and model seem to be presenting the correct array format.
Model
class People_model extends CI_Model{
function __construct() {
parent::__construct();
}
function get_person($name) {
$mode = $this->uri->segment(3);
$this->db->select("id, CONCAT(firstName,' ', lastName) AS name, type",FALSE);
$this->db->from('people');
if($mode == 'signin')
$this->db->where("status !=", "enter");
else
$this->db->where("status", "enter");
$this->db->like("concat(firstName,' ', lastName)", $name);
$this->db->order_by('name');
$query = $this->db->get();
if($query->num_rows > 0){
foreach ($query->result_array() as $row){
$new_row['value']=htmlentities(stripslashes($row['name']));
$new_row['id']=htmlentities(stripslashes($row['id']));
$row_set[] = $new_row; //build an array
}
}
echo json_encode($row_set); //format the array into json data
}
}
Controller (relevant functions)
function get_person() {
$this->config->set_item('disable_template', TRUE);
$this->load->model('People_model');
$name = $this->input->get_post();
$this->People_model->get_person($name);
}
function dosigninout() {
$mode = $this->uri->segment(3);
switch($mode) {
case 'signin':
$mode = 'enter';
break;
case 'signout':
$mode = 'exit';
break;
default:
$this->load->view("home/error", array('error' => "Invalid mode specified."));
}
$meeting = $this->_currentMeeting();
$person = $this->input->post('person_id');
if(!$this->_validPerson($person, $this->input->post('name'))) $this->load->view("home/error", array('error' => "You requested an operation with ".$this->input->post('name')." who has an ID of $person. The name and ID don't match."));
$this->db->insert("attendance", array('person_id' => $person, 'meeting_id' => $meeting['meetingID'], 'type' => $mode));
$this->db->where("id", $person);
$this->db->update("people", array('status' => $mode));
$redirectTo = (isset($_POST['redirect'])) ? $this->input->post('redirect') : false;
if($redirectTo) redirect($redirectTo);
else redirect('attendance');
}
Sample JSON data returned
[{"value":"Anna Woodhouse","id":"2"},{"value":"Elaine Woodhouse","id":"4"}]
View
$baseURL = base_url();
$extraHeadData = "";
?>
<h2><?=$title?></h2>
<p>Current meeting: <?=$meetingTitle?> on <?=$meetingDate?>.</p>
<?=form_open("attendance/dosigninout/$mode", array('id' => "signInOutForm"))?>
<fieldset>
<legend>Whom do you want to sign <?=($mode == "signin") ? 'in' : 'out'?>?</legend>
<div class="control-group">
<div class="controls">
<input type="hidden" name="person_id" id="person_id" value="" />
<input class="people-typeahead" type="text" id="typeahead" name="name" placeholder="person's full name"/>
</div>
</div>
</fieldset>
<div class="form-actions">
<?=form_submit('','Save changes','class="btn btn-primary"'); ?>
</div>
</form>
<script src="http://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.4.4/underscore-min.js"></script>
<script src="<?php echo $baseURL?>assets/js/typeahead.min.js"></script>
<script>
$(function($) {
$('input.people-typeahead').typeahead({
name: 'people',
remote: 'http://localhost/badgeentry/index.php/attendance/get_person',
dataType: 'json'
});
$("#people-typeahead").on("typeahead:selected typeahead:autocompleted", function(e,datum) {
$(person_id).val() = datum.id
});
});
</script>
In the form field I get the correct drop down list, but when an item is selected any new database entry has an id of "0" instead of the selected name id. I'm almost certain that this is an issue with the javascript code in the view not being correct, but quite frankly, I have no js skills to sort it out!
I see an issue here :
$(person_id).val() = datum.id
You are using jQuery's .val() incorrectly and the use of the selector is wrong too. It should look like :
$("#person_id").val(datum.id);
jQuery .val() documentation
I finally figured out how to get this working. Part of the problem was that I could find no examples of using typeahead.js in CodeIgniter that showed how the various script, view, controller and model components interact. I tried switching to Twitter bootstrap typeahead. However, despite finding references to using it with an arrays rather than a string, I still could not get a working solution.
In the end I went back to Twitter typeahead and started from scratch. I found this tutorial helped enormously:
Twitter Bootstrap typeahead.js with underscore.js Templating – A Tutorial - Alan Greenblatt
I'm posting what worked for me in case it can help anyone else with similar issues. This version also includes setting the remote source as a variable which allowed me to define it through PHP so that I could select data in the model based on the URL.
Model
class People_model extends CI_Model{
function __construct() {
parent::__construct();
}
function get_person($name) {
$modeinout = $this->uri->segment(3);
$this->db->select("id, CONCAT(firstName,' ', lastName) AS name, type",FALSE);
$this->db->from('people');
if($modeinout == 'signin'){
$this->db->where('status !=', 'enter');
}
else {
$this->db->where('status', 'enter');
}
$this->db->like("concat(firstName,' ', lastName)", $name);
$this->db->order_by('name');
$query = $this->db->get();
if($query->num_rows > 0){
foreach ($query->result_array() as $row){
$new_row['name']=htmlentities(stripslashes($row['name']));
$new_row['id']=htmlentities(stripslashes($row['id']));
$row_set[] = $new_row; //build an array
}
}
echo json_encode($row_set); //format the array into json data
}
Controller (relevant functions)
function signin() {
$this->load->helper("form");
$this->template->javascript('assets/js/underscore-min.js');
$this->template->javascript('assets/js/typeahead.min.js');
$data = $this->_currentMeeting();
$data['title'] = "Sign Someone In";
$data['attributes_form'] = array('id' => 'signInOutForm','class' => 'form-horizontal validate', 'enctype' => 'multipart/form-data');
$data['mode'] = 'signin';
$this->load->view("home/attendance/signinout", $data);
}
function signout() {
$this->load->helper("form");
$this->template->javascript('assets/js/underscore-min.js');
$this->template->javascript('assets/js/typeahead.min.js');
$data = $this->_currentMeeting();
$data['attributes_form'] = array('id' => 'signInOutForm','class' => 'form-horizontal validate', 'enctype' => 'multipart/form-data');
$data['id'] = '';
$data['title'] = "Sign Someone Out";
$data['mode'] = 'signout';
$this->load->view("home/attendance/signinout", $data);
}
function get_people() {
$this->config->set_item('disable_template', TRUE);
$this->load->model('People_model');
$name = $this->input->post('query');
$this->People_model->get_person($name);
}
function dosigninout() {
$mode = $this->uri->segment(3);
switch($mode) {
case 'signin':
$mode = 'enter';
break;
case 'signout':
$mode = 'exit';
break;
default:
$this->load->view("home/error", array('error' => "Invalid mode specified."));
}
$meeting = $this->_currentMeeting();
$person = $this->input->post('person_id');
if(!$this->_validPerson($person, $this->input->post('person_name'))) $this->load->view("home/error", array('error' => "You requested an operation with ".$this->input->post('person_name')." who has an ID of $person. The name and ID don't match."));
$this->db->insert("attendance", array('person_id' => $person, 'meeting_id' => $meeting['meetingID'], 'type' => $mode));
$this->db->where("id", $person);
$this->db->update("people", array('status' => $mode));
$redirectTo = (isset($_POST['redirect'])) ? $this->input->post('redirect') : false;
if($redirectTo) redirect($redirectTo);
else redirect('attendance');
}
View
<?php
$baseURL = base_url();
$extraHeadData = "";
?>
<h2><?=$title?></h2>
<p>Current meeting: <?=$meetingTitle?> on <?=$meetingDate?>.</p>
<?=form_open("attendance/dosigninout/$mode", array('id' => "signInOutForm",'class' => "form-horizontal validate"))?>
<input type="hidden" name="person_id" id="person_id">
<?php echo validation_errors(); ?>
<fieldset>
<legend>Whom do you want to sign <?=($mode == "signin") ? 'in' : 'out'?>?</legend>
<div class="control-group">
<div class="controls">
<input type="text" placeholder="person's full name" name="person_name" id="person_name" class="person-typeahead">
</div>
</div>
</fieldset>
<div class="form-actions">
<?=form_submit('','Save changes','class="btn btn-primary"'); ?>
</div>
</form>
<script>
var person_url="<?php echo site_url('attendance/get_people')."/".$mode;?>";
$(function($) {
_.compile = function(templ) {
var compiled = this.template(templ);
compiled.render = function(ctx) {
return this(ctx);
}
return compiled;
}
$('.person-typeahead').typeahead({
template: '<p><strong><%= name %></strong>: <%= id %></p>',
name: 'people',
valueKey: 'name',
engine: _,
remote: (person_url),
dataType: 'json'
}).on('typeahead:selected typeahead:autocompleted', function(event, datum) {
$('#person_id').val(datum.id);
$('#person_name').val(datum.name);
});
});
</script>
<?=jquery_validate('attendance/signout');?>

Categories