Remove JSON object value Laravel from MySql database - laravel

I want to remove JSON object value from mysql database via eloquent. I have tried with this code it works but I have to pass array key "$.language[1]".
Here is JSON object {"name":"The Lord of the Rings:The Fellowship of the Ring","language":["Hindi","English","Spanish"]} stored in database.
Here I want to remove English language from all the records.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Book;
use DB;
class BookController extends Controller
{
public function store(){
$book = new Book;
$book->attributes = $jsonAttr;
$book->save();
echo "Book saved";
die;
}
public function updateLanguage()
{
$result = Book::where('attributes->language','LIKE','%English%')->update(['attributes' => DB::raw('JSON_REMOVE(attributes, "$.language[1]")')]);
//$result = Book::where('attributes->language','LIKE','%H%')->get();
echo "<pre>";
print_r($result);
die;
}
}
Any help would be appreciated.

Where condition fetch all the match record from Database. You need to loop this query to remove particular book language. Try this code...
public function updateLanguage()
{
//Get all matched records from database
$result = Book::where('attributes->language','LIKE','%')->get();
//Loop items to get unique id
foreach($result as $key => $val){
$id = $val['id'];
$attr = json_decode($val->attributes, true);
$data = $attr['language'];
foreach($data as $itemkey => $lang){
if($lang == "English"){
//Pass unique id to remove language from book record
$result = Book::where('id',$id)->update(['attributes' => DB::raw('JSON_REMOVE(attributes, "$.language['.$itemkey.']")')]);
}
}
}
$result = Book::where('attributes->language','LIKE','%')->get();
foreach ($result as $key => $value) {
print_r($value['attributes']);
echo "<br>";
}
die;
}

You need json_decode for transform json to array : link
You remove "English" in array with unset : link
After that you can json_encode for transform array to json.

Related

how to show unix timestamp in blade view from created_at or updated_at field in database laravel?

I want to get UNIX timestamp or convert created_at or updated_at date to UNIX timestamp format from database fields (created_at and updated_at) in laravel 5.8 , how can i do this?
this is my code in my controller :
public function viewArchives(){
$data = Archive::select(‘created_at’)->get();
return view(‘view.archives’, compact(‘data’));
}
and in view/archives.blade.php :
<?php echo $data;?>
the result is :
{“created_at”:”2019-03-17 19:10:30″}
but i want the result be like this :
{“created_at”:”1552849830″}
how can get this result?
$string = '2019-03-17 19:10:30';
$obj = new stdClass;
$obj->created_at = $string;
$collection = [$obj];
foreach ($collection as $k => &$v) {
$collection[$k]->created_at = strtotime($v->created_at);
}
//var_dump($collection);
or
$string = '2019-03-17 19:10:30';
$obj = new stdClass;
$obj->created_at = $string;
$collection = [$obj];
array_walk($collection, function (&$item, $key) {
$item->created_at = strtotime($item->created_at);
});
//var_dump($collection);
Or in your case
public function viewArchives()
{
$data = Archive::select('created_at')->get();
foreach ($data as $k => &$v) {
$v->created_at = strtotime($v->created_at);
}
return view('view.archives', compact('data'));
}
or
public function viewArchives()
{
$data = Archive::select('created_at')->get();
array_walk($data, function (&$item, $key) {
$item->created_at = strtotime($item->created_at);
});
return view('view.archives', compact('data'));
}
This is good place to use array_walk() function.
Add strtotime() view/archives.blade.php :
<?php echo strtotime( $data );?>
With an Eloquent Model one can actually define the $casts per column:
class SomeModel extends Model
{
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $casts = [
'created_at' => 'datetime'
];
}
If you want epoch timestamps instead, just remove this cast (which is likely present).
When the timestamp isn't from any Eloquent Model, one still can render it with Blade:
#php
$dt = new DateTime();
echo $dt->setTimestamp( $timestamp )->format("Y-m-d H:m:s");
#endphp
Or the other way around:
#php
echo strtotime( $isodate );
#endphp

How do i fetch session id from database to controller and compare codeigniter

It Return undefined index uname also try $row->name not working return false
public function profile() {
$this->load->view('header');
$uname = $this->session->userdata('uname');
$row = $this->brid_groom_fetch->get_program_specific_gender();
if ($row['uname']->uname == $uname) {
$session_id = $this->session->userdata('session_id');
var_dump($session_id);
} else {
echo 'fail';
}
}
First you need to assign session variables to an array.
Then your code
$id = $this->session->userdata('uname')
will be relevent.
To assign you can use
$this->session->set_userdata(
array(
'uname' => $row->name
)
);
Where $row->name is the value fetched from your model query.
The above sets the value in session variable 'uname'
Now you can use $id wherever you want
Also Check your autoload.php file under config dir
$autoload['libraries'] = array('session');
should be present there.
If not, then you can do the above or call
$this->load->library('session')
in your controller function.
See if that helps

codeigniter how to show data in functions

My model:
function get_data($id)
{
$this->db->select('id, Company, JobTitle');
$this->db->from('client_list');
$this->db->where('id', $id);
$query = $this->db->get();
return $query->result();
}
I want to get the the data from get_data(), is this the right way?
public function show_data( $id )
{
$data = $this->get_data($id);
echo '<tr>';
echo '<td>'.$data['Company'].'</td>';
echo '<td>'.$data['JobTitle'].'</td>';
echo '<td>'.$data['id'].'</td>';
echo '<td></td>';
echo '</tr>';
}
Use the row_array() function to get the data in the array format.
Reference url
http://ellislab.com/codeigniter/user-guide/database/results.html
you can use foreach loop to print
foreach ($data->result() as $row)
{
echo '<tr>';
echo '<td>'.$row['Company'].'</td>';
echo '<td>'.$row['JobTitle'].'</td>';
echo '<td>'.$row['id'].'</td>';
echo '<td></td>';
echo '</tr>';
}
thank you
just to improve answer, I use "general_model" for all my controllers, there are some exceptions where I need special queries, I just create desired model so "general_model" stays same and I can use it in any project.
e.g.
general_model.php
function _getWhere($table = 'table', $select = 'id, name', $where = array()) {
$this->db->select($select);
$q = $this->db->get_where('`'.$table.'`', $where);
return ($q->num_rows() > 0) ? $q->result() : FALSE;
}
.
.
.
//bunch of another functions
in controller I just call
$this->data['books'] = $this->general_model->_getWhere('book', '*', array('active' => '1'));
$this->render('book_list_view'); // $this->load->view('book_list_view', $this->data);
sidenote: I am extending CI_Controller therefore I use $this->data['books'] instead $data['books'] to pass data into view
in view
//check if there are any data
if ($books === FALSE) {
//some error that there are no books yet
} else {
//load data to table or something
foreach ($books as $book) {
$book->id; // book id
}
}

Codeigniter num_row returns "array" instead of number

Alright, Im trying to count all the rows where "Membership_Status" = Active. The result I get right now is "Array" instead of a number.
Here is my model
class Report_model extends Model
{
function count_members()
{
$query = $this->db->get_where('Membership', array('Membership_Status' => 'Active'));
return $query->num_rows();
}
}
Here is my controller
class Report extends Controller {
function YTD_report()
{
$data['main_content'] = 'report_membership_view';
$this->load->view('includes/template', $data);
}
}
Here is my view
report_model->count_members();
echo $total;
?>
My result is Array, where according to the db info, it should be 4.
What can I do/change to get it to display the proper number?
thanks
the $data array your passing to the view will create one variable for each key to be used by view...
So your controler once the model is loaded, you should do:
$data['total'] = $this->Report_model->count_members();
Then in the view you can use the $total variable like this:
<?php echo $total; ?>

codeigniter view, add, update and delete

I'm newbie in codeigniter and still learning. Anyone can help for sample in basic view, add, update, delete operation and queries in codeigniter will gladly appreciated.
Just a simple one like creating addressbook for newbie.
thanks,
best regards
Some sample queries in Codeigniter
class Names extends Model {
function addRecord($yourname) {
$this->db->set("name", $yourname);
$this->db->insert("names");
return $this->db->_error_number(); // return the error occurred in last query
}
function updateRecord($yourname) {
$this->db->set("name", $yourname);
$this->db->update("names");
}
function deleteRecord($yourname) {
$this->db->where("name", $yourname);
$this->db->delete("names");
}
function selectRecord($yourname) {
$this->db->select("name, name_id");
$this->db->from("names");
$this->db->where("name", $yourname);
$query = $this->db->get();
return $this->db->result();
}
function selectAll() {
$this->db->select("name");
$this->db->from("names");
return $this->db->get();
}
}
More information and more ways for CRUD in codeigniter active record documentation
More about error number over here
A sample controller
class names_controller extends Controller {
function addPerson() {
$this->load->Model("Names");
$name = $this->input->post("name"); // get the data from a form submit
$name = $this->xss->clean();
$error = $this->Names->addRecord($name);
if(!$error) {
$results = $this->Names->selectAll();
$data['names'] = $results->result();
$this->load->view("show_names", $data);
} else {
$this->load->view("error");
}
}
}
More about controllers over here
A sample view - show_names.php
<table>
<tr>
<td>Name</td>
</tr>
<?php foreach($names as $row): ?>
<tr><td><?ph echo $row->name; ?></td></tr>
<?php endforeach; ?>
</table>
More about codeigniter views over here
You can use this as an example
class Crud extends Model {
// selecting records by specifying the column field
function select()
{
// use $this->db->select('*') if you want to select all the records
$this->db->select('title, content, date');
// use $this->db->where('id', 1) if you want to specify what row to be fetched
$q = $this->db->get('mytable');
// to get the result
$data = array();
// for me its better to check if there are records that are fetched
if($q->num_rows() > 0) {
// by doing this it means you are returning array of records
foreach($q->result_array() as $row) {
$data[] = $row;
}
// if your expecting only one record will be fetched from the table
// use $row = $q->row();
// then return $row;
}
return $data;
}
// to add record
function add()
{
$data = array(
'title' => 'My title' ,
'name' => 'My Name' ,
'date' => 'My date'
);
$this->db->insert('mytable', $data);
}
// to update record
function update()
{
$data = array(
'title' => $title,
'name' => $name,
'date' => $date
);
$this->db->where('id', 1);
$this->db->update('mytable', $data);
}
// to delete a record
function delete()
{
$this->db->where('id', 1);
$this->db->delete('mytable');
}
}
Some of this are from codeigniter userguide.
To view the records,
If return data is array of records,
foreach($data as $row)
{
echo $row['title'] . "<br />";
}
If the return data is an object (by using $q->row),
echo $data->title;
This is just a few examples or CRUD in Codeigniter. Visit the codeigniter userguide.

Resources