Laravel Activity Log won't work on Update and Delete - laravel

I'm using SPATIE laravel-activitylog I followed all the instructions but still, it only logs the Create function not update and delete while using it on a Modal
My Modal
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Spatie\Activitylog\Traits\LogsActivity;
class z_education extends Model
{
//
use LogsActivity;
protected $fillable = [
'user_id',
'type',
'school_name',
'degree',
'isremoved',
];
protected static $logFillable = true;
}
My Controller
public function delete_user_education($id)
{
z_education::where('id', $id)->delete();
return back();
}

Your controller query is executed via the Query Builder, instead of an Eloquent Model. So there will be no model events to listen to.
Retrieve and delete the model itself to fire and log the events:
$model = z_education::findOrFail($id);
$model->delete();
return back();

Related

Laravel 6.2 whereHasMorph not returning expected value

Need some help for laravel polymorphic. I'm trying to filter from the main table which is Comment to get its morph tables and search for the key word FOO. I have tried with whereHas but get error saying to use whereHasMorph so I tried changing whereHas to whereHasMorph. But every time i filter, the result will be an empty collection even if the value exist in the table. So I went through laravel documentation and found the below sample. I tried the sample but I'm still getting an empty collection. I have tried reading but could not find a fix.
Below is the sample code which I have tried
** Models **
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Comment extends Model
{
protected $table = 'comments';
protected $fillable = [
'body',
'commentable_id',
'commentable_type'
];
public function commentable()
{
return $this->morphTo();
}
}
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
protected $table = 'posts';
protected $fillable = [
'title',
'body'
];
public function comments()
{
return $this->morphMany('App\Comment', 'commentable');
}
}
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Video extends Model
{
protected $table = 'videos';
protected $fillable = [
'title',
'url'
];
public function comments()
{
return $this->morphMany('App\Comment', 'commentable');
}
}
** Controller **
public function commentList () {
$comments = App\Comment::whereHasMorph(
'commentable',
['App\Post', 'App\Video'],
function ($query) {
$query->where('title', 'like', '%foo%');
}
)->get();
dd($comments);
}
Is there anything I'm missing out or do i need to configure something or install some packages ?
"php": "^7.2",
"laravel/framework": "^6.2",
Images of DB table
I have tried and dont know why suddenly work when i remove the first \ in the DB.
Changed \App\Post in the table to App\Post and also in the code then it work already. Thanks for all the help.

Laravel5 event 'deleting' doesn't work on Model::whereIn()

I have one to many relation on the user model, I have set an event when I delete the user will dell all Childs client.
on the resource, the Controller destroys method event 'deleting' method is work for normally.
But I create a mass massDestroy method using Model::whereIn() deleting event doesn't work.
Below is my related code, How can I fix it?
UsersController relate code
public function destroy(User $user)
{
$user->delete();
return back();
}
public function massDestroy(MassDestroyUserRequest $request)
{
if ($request->ajax()) {
User::whereIn('id', $request->get('ids'))->delete();
}
return response(null, Response::HTTP_NO_CONTENT);
}
User Model relate code
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use SoftDeletes, Notifiable;
public $table = 'users';
//skip
protected static function boot()
{
parent::boot();
self::deleting(function (User $user) {
$user->clients()->delete(); //doesn't work on Model::whereIn
});
}
public function clients()
{
return $this->hasMany(Client::class, 'user_id', 'id');
}
}
Client model relate code
public function user()
{
return $this->belongsTo(User::class ,'user_id', 'id');
}
PS* I have try to delete one by one( very ugly code ) as below is normally work.
UsersController
public function massDestroy(MassDestroyUserRequest $request)
{
if ($request->ajax()) {
$users = User::whereIn('id', $request->get('ids'))->get();
foreach ($users as $user ) {
$user ->delete();
}
}
return response(null, Response::HTTP_NO_CONTENT);
}
It is clearly stated in laravel documentation that if you need to perform mass operations then none of the events will be fired. You need to delete them one by one using foreach.
When executing a mass delete statement via Eloquent, the deleting and deleted model events will not be fired for the deleted models. This is because the models are never actually retrieved when executing the delete statement.
Please check note option in Deleting Models
You are using function get() to retrieve a collection of records and there is no method delete() on collection, either you delete by using first() function or delete them by looping the collection array.
I hope you got your answer
I have a trick for your problem
It is clearly stated in Laravel documentation Deleting Models that if you need to perform mass operations then none of the events will be fired.
When executing a mass delete statement via Eloquent, the deleting and deleted model events will not be fired for the deleted models. This is because the models are never actually retrieved when executing the delete statement.
My Trick is:
Use this code
$ids = User::whereIn('id', $request->get('ids'))->pluck('id');
User::destroy($ids);
instead of
//User::whereIn('id', $request->get('ids'))->delete();

Laravel: a simple MVC example

I'm new to Laravel and the documentation's basic task list returns Views from the Route(web.php) but I want to use a Controller to return an image file.
So I have for my route:
Route::get('/products', 'ProductController#index');
Then my ProductController action (please ignore comments as I'm using index to simplify things):
<?php
namespace App\Http\Controllers;
use App\Product;
use Illuminate\Http\Request;
class ProductController extends Controller
{
/**
* Display a listing of the resource.
*
#return \Illuminate\Http\Response
Fetch and return all product records.
*/
public function index()
{
//
//return response()->json(Product::all(), 200);
return view('/pages/product', compact('product'));
}
And my product.blade.php (nested in views/pages/product):
<img src="/images/product/Frozen_Ophelia_800x.png">
I keep getting a ReflectionException Class App\Product does not exist.
I got this working when I just returned a view from the route. I'm getting a ReflectionException
Class App\Product does not exist so I think it's something at the top, ie. use App\Product; that is wrong.
Edit (below is my App\Product nested in app/Providers):
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Product extends Model
{
//
use SoftDeletes
protected $fillable = [
'name', 'price', 'units', 'description', 'image'
];
public function orders(){
return $this->hasMany(Order::class);
}
}
Assuming App\Product model exists, correct code should be:
public function index() {
$product = Product::all();
return view('pages.product', compact('product'));
}
Check the docs.
PS did you call a $ composer dumpautoload? ReflectionException Class error is often related to new class autoloading (eg. new classes in a packages)
view function should have any view template not any url or route. Of you have file views/pages/product.blade.php then use
view('pages.product',compact('product'));

laravel voyager soft delete issue

I'm trying to get soft deleting work on laravel voyager but everytime I delete a post it's also deleted in my database.
here is my post model :
<?php
namespace App;
use TCG\Voyager\Traits\Resizable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use App\Category;
class Post extends Model
{
use Resizable;
use SoftDeletes;
protected $dates = ['deleted_at'];
public function category()
{
return $this->belongsTo(Category::class);
}
public function scopeIspublished($query)
{
return $query->where('status','published');
}
}
I added a column deleted_at to my posts table as well.
Thanks for helping

Laravel 5.2 eloquent returns soft deleted records

I am using Laravel 5.2.
I have a model as below:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\SoftDeletes;
class ZoomMeeting extends BaseModel {
public $timestamps=true;
protected $table = 'zoom_meetings';
use SoftDeletes;
protected $dates = ['deleted_at'];
protected $fillable = ['user_id', 'uuid', 'meeting_id', 'host_id', 'topic', 'status', 'type', 'start_url', 'join_url', 'created_at'];
public function users() {
return $this->belongsTo('App\Models\User');
}
}
And the base model is as below:
<?php namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Auth;
use Carbon\Carbon;
class BaseModel extends Model {
public $timestamps = false;
protected static function boot()
{
//parent::boot();
static::creating(function($model) {
if(empty($model->created_at))
{
$model->created_at = date('Y-m-d H:i:s');
}
return true;
});
static::updating(function($model) {
$model->updated_at = date('Y-m-d H:i:s');
return true;
});
}
}
I am using softdeletetrait in ZoomMeeting model, and soft deleting is working fine.
However, if I fetch records from the same model using eloquent, it returns the soft deleted records too. I am using code below to get the records:
$record = ZoomMeeting::where("user_id", $user_id)->where("meeting_id", $meeting_id)->orderBy("id", "DESC")->first();
The eloquent is building the query as:
select * from `zoom_meetings` where `user_id` = 3 and `meeting_id` = 707070707 order by `id` desc limit 1
See, there is no deleted at is null set in where statement. It is not preventing the deleted records.
I am not sure where am I making mistake?
It looks like you are overriding the boot method, but you aren't ever actually calling the parent boot method (it's commented out), so the trait is never getting initialized correctly. I believe that also means the data you have been deleting is actually being deleted from the database.
Is there a reason you need to override the boot method? What you are adding is already done handled by the framework, so it doesn't appear to be necessary.

Resources