Laravel API delete row from db - laravel

While trying to delete rows by id from db as below , I am getting the error- count(): Parameter must be an array or an object that implements Countable. I think no id is passed to the delete() function in my code and am not sure how to pass it. Please help me with ur suggestions.
Controller
public function delete($id){
$data = PersonalDetails::where('id',$id)->delete();
// dd($data);
if(count($data)){
return response()->json(['message'=>'Successfully Deleted']);
}
else{
return response()->json(['message'=>'Delete Failed']);
}
}
Route
Route::group([
'namespace'=>'App\Http\Controllers',
'middleware' => 'api',
], function ($router) {
Route::post('delete/{id}', 'PersonalDetailsAdmin#delete');
}

The ->delete() method already returns the count of the deleted rows, so the solution would be:
public function delete($id){
$count = PersonalDetails::where('id',$id)->delete();
// dd($data);
if($count > 0 ){
return response()->json(['message'=>'Successfully Deleted']);
}
else{
return response()->json(['message'=>'Delete Failed']);
}
}

Related

How to remove or unfriend through API

This is database structure
This is API
Route::post('/friend', 'FriendController#index');
Route::post('/removerequest/{id}', 'FriendController#removerequest');
This is controller code which into friend request method and remove method, but error in remove friend method..
public function index(Request $request) {
$sender = Friend::where('sender_id', $request->sender_id)->where('receiver_id',$request->receiver_id)->first();
if(empty($sender)){
Friend::create(['sender_id'=>$request->sender_id,'receiver_id'=>$request->receiver_id, 'approved'=>'pending']);
$response = ['message'=>'Friend Request has been sent','status'=>200];
return response()->json($response);
}else{
$response = ['message'=>'Request has been sent already','status'=>200];
return response()->json($response);
}
}
public function removerequest($id){
$friends = Friend::all()
->where('receiver_id')
->where('sender_id')
->approved('accept')
->delete();
}
Error is
BadMethodCallException: Method Illuminate\Database\Eloquent\Collection::approved does not exist. in file /home/ynvih0l26evc/public_html/vendor/laravel/framework/src/Illuminate/Support/Traits/Macroable.php on line 104
enter code here
Update your Route to
Route::delete('/removerequest/{id}', 'FriendController#removerequest');
//change
->approve('approved', 'accept')
to
->where('approved', 'accept')
Update your controller method to
public function removerequest($id){
$friends = Friend::Find($id)->delete(); //see update here
//->where('receiver_id')
//->where('sender_id')
//->where('approved', 'accept')
//->delete();
}
OR
public function removerequest($id){
Friend::where( ['id' => $id, 'approved' => 'accept'])->delete();
}

Laravel Eloquent : Getting object instead of array

Trying to get a hotel in detail for hotel management API, in which for some hotels, getting
$hotel->rooms
as object and for some as array. The eloquent query in Hotel model as below.
public function detail($hotelid) {
return $this->with(['rooms','roomType'])->find($hotelid);
}
public function rooms() {
return $this->hasMany(HotelRooms::class, 'hotels_id')->where('status','active');
}
HotelRoom Model
public function roomType(){
return $this->hasOne(RoomType::class,'id','room_type_id')->where('status','active');
}
Controller
public function __construct(){
$this->model = new Hotel();
}
public function hotelDetail(Request $request){
$data = $this->model->detail($request->input('hotel_id'));
foreach($data->rooms as $key=>$room){
if(!$room->roomType){
unset($data->rooms[$key]);
continue;
}
}
return response()->json([
'status' => true,
'status_message' => 'successful',
'data' => $data,
]);
}
response
{
"id":"id",
"name":"name",
"rooms":{
"1":{},
"2":{}
}
}
{
"id":"id",
"name":"name",
"rooms":[
{},
{},
]
}
When you use unset on array, your array indexes remain for each item. Same as for collection->filter() or for array_filter() that is actually used in collection->filter(). That is why you need to rebuild the indexes:
$data->rooms = array_values($data->rooms->toArray());
to reindex the array.
Or use the foreach, but push values to new array:
$filteredRooms = [];
foreach($data->rooms as $key=>$room){
if(!$room->roomType){
continue;
}
$filteredRooms[] = $room;
}
$data->rooms = $filteredRooms;
Or instead of foreach loop, use filter for collection in combination with values() :
$filteredRooms = $data->rooms->filter(function ($room, $key) {
return (!$room->roomType)? false : true;
})->values();
After filtering array you have to re-index your array.
foreach($data->rooms as $key=>$room){
if(!$room->roomType){
unset($data->rooms[$key]);
continue;
}
}
$data->rooms = $data->rooms->values();

Codeigniter - Trying to count articles view

Im working with codeigniter and have a controller and 3 model functions to read, insert and update a column of table.
i want to get count of view from db and update it per each view!
but after the update an extra row added to table! with zero value for content_id.
please check once!
this is my controller:
public function daily_report($id="")
{
$counter=$this->home_model->counter($id);
if($counter)
{
$view=$this->home_model->counter($id)->row()->view;
$views=$view+1;
$this->home_model->update_counter($views,$id);
}
else{
$views=1;
$this->home_model->set_counter($views,$id);
}
}
This is the model functions:
public function counter($id)
{
$code=$id;
$lang=$this->session->userdata('lang');
$data = $this->db
->select('view')
->from('tbl_views')
->where("content_id",$code)
->where("language",$lang)
->get();
if ($data->num_rows() > 0) {
return $data;
}else{
return false;
}
}
public function set_counter($views,$id)
{
$data = array(
'content_id' => $id ,
'view' => $views,
'language'=>$this->session->userdata('lang')
);
$this->db->insert('tbl_views', $data);
}
public function update_counter($views,$id)
{
$data = array(
'view' => $views,
);
$this->db->where('content_id', $id);
$this->db->update('tbl_views', $data);
}

CodeIgniter just show one result from my table

SELECT * FROM image;
I am using that query to get data from image table, when i checked it using this query directly into mysql commandline it showed 3 result like this
3 rows in set (0.00 sec);
but, when i try to fetch it from codeigniter using query or active_record, it just show me 1 result. This is my code
class Produk_model extends CI_Model{
function __construct(){
parent::__construct();
}
function get_phome(){
$this->db->select('nama_produk, nama_seo, nama_kategori, seo_kategori, nominal_harga');
$this->db->join('kategori','kategori.id_kategori=produk.id_kategori');
$this->db->join('harga','harga.id_produk=produk.id_produk');
$q=$this->db->get('produk');
if($q->num_rows()){
return $q;
}
}
function get_all_pimage(){
$q=$this->db->get('image');
if($q->num_rows()>0){
return $q;
}
}
function get_by_kategori($kategori_name=''){
$this->db->select('nama_kategori, seo_kategori, nama_produk, nama_seo, nominal_harga, url_img');
$this->db->join('kategori', 'kategori.id_kategori=produk.id_kategori');
$this->db->join('harga','harga.id_produk=produk.id_produk');
$this->db->join('image','image.id_produk=produk.id_produk');
$this->db->where('seo_kategori',$kategori_name);
$q=$this->db->get('produk');
if($q->num_rows()){
return $q;
}
}
function get_by_produk($produk_name=''){
$this->db->select('produk.id_produk, nama_produk, nama_seo, short_desc, min_beli, nominal_harga');
$this->db->join('produk_detil','produk_detil.id_produk=produk.id_produk');
$this->db->join('harga','harga.id_produk=produk.id_produk');
$this->db->where('nama_seo', $produk_name);
$q=$this->db->get('produk');
if($q->num_rows()){
return $q;
}
}
function get_img_by_produk($produk_id=''){
$this->db->select('url_img');
$this->db->where('id_produk', $produk_id);
$q=$this->db->get('image');
if($q->num_rows()){
return $q;
}
}
}
i am trying to use get_all_pimage() with the function below from my controller
function home(){
$this->load->model('produk_model');
$data['konten']=$this->produk_model->get_phome()->result();
$data['img']=$this->produk_model->get_all_pimage()->row_array();
$this->load->view('frontend/home', $data);
}
but it just showed me 1 result, like this :
Array
(
[id_image] => 2
[id_produk] => PRD002
[seo_image] => pastel-1
[url_img] => pastel-1.jpg
)
i am confused, why it can be happened. because i don't know where is the mistake . Thank for your helping
Change function to..
function get_all_pimage(){
$q=$this->db->get('image');
if($q->num_rows()>0){
return $q->result_array();
}
}
Take row->Array() off your call...like so..
$data['img']=$this->produk_model->get_all_pimage();
Then foreach...
foreach($data['img'] as $val){
//display you data
}

codeigniter call to a member function row() on a non-object

I've searched the ends of the earth and back for this solution, and for everyone else, the fix was to autoload the database class in autoload.php. However, I am already doing this, so I don't know where else to go with it.
Controller:
class Login extends CI_Controller{
function validate_credentials(){
$this->load->model('membership_model');
// call the member function from membership_model.php
$q = $this->membership_model->validate();
if($q){
// user info is valid
$data = array(
'username' => $this->input->post('username'),
'is_logged_in' => true
);
$this->session->set_userdata($data);
redirect('site/members_area');
}else{
$this->index();
}
}
}
Model:
class Membership_model extends CI_Model{
function validate(){
// this method is called from the login.php controller
$this->db->where('username', $this->input->post('username'));
$this->db->where('password', md5($this->input->post('password')));
$q = $this->db->get('members');
if($q->num_rows == 1){
return true;
}
return false;
}
}
Any help on this please, I'm going round in circles with this
My next thought is that php.ini needs configuring on my host server, to load the mysql modules - but I would very surprised by this?
Just to clarify - the line:
if($q->num_rows)
Is the problem, saying that I am trying to reference a property of a non object
Actually
if($q->num_rows)
should be
if($q->num_rows()) // It returns the number of rows returned by the query.
So you can use
if($q->num_rows()) // In this case it'll be evaluated true if rows grater than 0
{
// code when rows returned
}
num_rows is a function.
if ($query->num_rows() > 0) {
}
So you need
if($q->num_rows() > 0) {
return true;
}
Solved - I hadn't assigned a User to the database, therefore couldn't access it.
Relief

Resources