Laravel - catch all eloquent requests - php

As we can read here, we can listen the eloquent events and use it in the AppServiceProvider. It goes like this:
public function boot()
{
User::creating(function ($user) {
Log::create(['message' => 'create method']);
});
User::deleting(function ($user) {
Log::create(['message' => 'delete method']);
});
}
For all my eloquent models, I want to log in the database when it is created and who created it. This would mean that I need to copy paste this snippet 20 times and only change the User::creating part.
Is there a way that I can catch the eloquent events from all models and make something like this:
public function boot()
{
AllModels::creating(function ($model) { // <--- something like this here?
Log::create([
'message' => 'create method',
'model' => get_class($model) // <--- and then get the class name
]);
AllModels::deleting(function ($user) {
/***/
}
});
}

You can try something like this:
$models = ['User', 'Post', 'Comment', ....];
foreach ($models as $model) {
$model::creating(....);
$model::deleting(....);
}
Similar approach worked for me (I used DI instead of facades though).
Another approach I found and bookmarked some time ago:
Event::listen(['eloquent.creating: *'], function() {
....
});

Related

message: The POST method is not supported for this route. Supported methods: GET, HEAD, PUT, PATCH, DELETE

So I have an API route
Route::group(['prefix' => 'users'], function() {
Route::group(['prefix' => 'seminar'], function() {
Route::get('/{employee_number}', [UserProfileController::class, 'getSeminar']);
Route::post('/{user}', [UserProfileController::class, 'createSeminar']);
Route::put('/{seminar}', [UserProfileController::class, 'updateSeminar']);
Route::delete ('/{seminar}', [UserProfileController::class, 'deleteSeminar']);
});
});
And a controller
public function createSeminar(User $user, Request $request)
{
return $this->allowIfRecordOwner($user->id, function() use ($user, $request) {
$seminar = Seminar::create([
"user_id" => $user->id,
"dates" => $request->dates,
"name" => $request->name,
"certificate_number" => $request->certificate_number
]);
return response()->json($seminar->toArray(), 200);
});
}
And im using that from my angular app
private saveSeminar(index) {
event.preventDefault();
const seminar = this.userSeminars[index];
if (seminar.id) {
this.updateUserSeminar(index);
} else {
this.storeStudentAddress(index);
}
}
private storeStudentAddress(index) {
this.apiService.create('users/seminar', this.userSeminars[index])
.subscribe(
response => {
this.userSeminars[index].edit = false;
this.userSeminars[index].id = response.id;
this.getUserSeminar(index.employee_number);
this.toastr.success('Seminar Successfully saved', 'Success');
});
}
I have done php artisan route:list and found my router here
And I have now been staring at the error for over three hours and can't see why I'm getting the error. Any help would be wonderful
Your API endpoint in Laravel doesn't look like it lines up with your API endpoint in your JavaScript.
You need to hit this endpoint in order to create a seminar: api/users/seminar/{user}, where {user} is the user's ID.
Your line here: this.apiService.create('users/seminar', this.userSeminars[index]) looks like it's instead hitting api/users/seminar, without the user's ID appended to the end.
You just need to change it to this.apiService.create('users/seminar/' + USER_ID, ... where USER_ID is whatever variable you're using to store the user's ID, or alternatively a method which returns it.

Axios GET with params being ignored

Newbie to all the tech I'm using here.
Trying to query a table using Axios in Laravel with Vue.js. Here's what I got:
from my component's <script>
this.axios
.get('http://localhost:8000/api/tasks', {params: {vid: this.properties[0].vid}})
.then(response => {
this.tasks = response.data;
console.log(response)
})
Regardless of what vid is in the params, the response contains ALL of the table's rows.
I do know that this may have something to do with api.php, and the Controller associated with the request. I'll post those to be verbose.
routes/api.php
Route::middleware('api')->group(function () {
Route::resource('vehicles', VehicleController::class);
Route::resource('tasks', TaskController::class);
Route::get('tasks?={vid}', [TaskControler::class, 'search']);
});
Controllers/TaskController.php
class TaskController extends Controller
{
//
public function index() {
$tasks = Task::all()->toArray();
return $tasks;
}
public function store(Request $request){
$task = new Task([
'make' => $request->input('make'),
'model' => $request->input('model'),
'year' => $request->input('year'),
'mileage' => $request->input('mileage'),
'type' => $request->input('type'),
'VIN' => $request->input('VIN')
]);
$task->save();
}
public function show($tid){
$task = Task::find($tid);
return response()->json($task);
}
public function update($tid, Request $request){
$task = Task::find($tid);
$task->update($request->all());
return response()->json('Task Updated!');
}
public function destroy($tid){
$task = Task::find($tid);
$task->delete();
return response()->json('Task Deleted!');
}
}
I tried for a while to mess around with api and the controller, but to no avail. Most of the questions asked here give "just use params" as an answer, but despite my best efforts I don't seem to be able to get away with "just" params (willing to be proven wrong.)

Weird Laravel DB Listener make Query insert return wrong ID [SOLVED]

Im facing a weird maybe a bugs or my mistake where Eloquent create return wrong ID. It's happen when I put DB::listen in service provider class and store in database any queries detected in DB::listen.
BUT the weird is When i trying to insert like this User::create($input), it's return the ID of QueryActivity not the ID of User. For example the ID should be 20 but its return 100 from table QueryActivity
logs from User::create($input)
[2020-02-23 12:42:46] staging.INFO: {"first_name":"Testing","last_name":"Tesgin","username":"Testing","staff_id":"12313123","mobile_phone":"01231232323","active":true,"email":"testing#gmail.com","created_by":1,"updated_at":"2020-02-23 12:42:46","created_at":"2020-02-23 12:42:46","id":123,"fake_password":"5ebe2294ecd0e0f08eab7690d2a6ee69"}
Above Logs, the highlighted only the ID is wrong. Other detail is correct.
Eloquent
$user = User::create($input);
And in my ObserverServiceProvider.class
DB::listen(function ($query) {
try {
if (preg_match('(query_activities)', $query->sql) == 0) {
QueryActivity::createUsingQueryBuilder([
'connection_name' => $query->connectionName,
'time_taken' => $query->time,
'query' => $query->sql,
'bindings' => Utils::aesEncrypt(json_encode($query->bindings)),
'created_at' => now(),
'updated_at' => now(),
]);
}
} catch (\Exception $exception) {
LogCentre::channel('query')->info($exception->getMessage());
}
});
in QueryActivity class
class QueryActivity extends Model
{
protected $fillable = [
'connection_name',
'time_taken',
'query',
'bindings'
];
public static function createUsingQueryBuilder(array $activity)
{
DB::connection((new self)->getConnectionName())->table((new self)->getTable())->insert($activity);
}
}
Is there anyone facing this issues?
SOLUTION:
Based on issues in https://github.com/laravel/framework/issues/25768#issuecomment-424179984
Change connection name then its working..

Creating a url structure like current-route/edit/{id} in laravel 5

I am very much new to Laravel. During the learning curve I came across a situation which I am going to describe below :
I have a page contains data grid in /manage-clients route. For the grid I am used datatables. I have added edit button for each record. Now, I want to make the edit screen, which is basically a new view. I want the url structure for edit to be /manage-clients/edit/{id}. How to achieve this with the below set-up.?
below is my controller :
public function getIndex()
{
return View('admin.manageclients');
}
public function anyData()
{
$clients = DB::table('users')
->select(['id', 'first_name', 'last_name', 'email', 'created_at', 'updated_at'])
->where('type', '=', '');
return Datatables::of($clients)->addColumn('action', function ($clients) {
return '<i class="glyphicon glyphicon-edit"></i> Edit';
})->editColumn('id', 'ID: {{$id}}')->make(true);
}
public function editClient($id)
{
//This is my edit function which is going to load the details of provided $id into view.
return $id;
}
My route is :
Route::group (array('prefix' => 'admin', 'middleware' => 'auth'), function()
{
Route::get('dashboard',['as'=>'getDashboard', 'uses'=>'Admin\AdminController#getDashBoard']);
Route::controller('manage-admins', 'Admin\ManageAdminController', ['anyData' => 'manage-admins.data','getIndex' => 'manage-admins']);
Route::controller('manage-clients', 'Admin\ManageClientController', ['anyData' => 'manage-clients.data', 'getIndex' => 'manage-clients']);
});
Do you mean something like this?
Route::group (array('prefix' => 'admin', 'middleware' => 'auth'), function()
{
Route::get('dashboard',['as'=>'getDashboard', 'uses'=>'Admin\AdminController#getDashBoard']);
Route::controller('manage-admins', 'Admin\ManageAdminController', ['anyData' => 'manage-admins.data','getIndex' => 'manage-admins']);
Route::controller('manage-clients', 'Admin\ManageClientController', ['anyData' => 'manage-clients.data', 'getIndex' => 'manage-clients']);
Route::get('manage-clients/edit/{id}', 'ManageAdminController#editClient');//I have added this code
});
Note that id will be automatically be available to you inside the controller

Laravel force delete generates NotFoundHttpException

I have read as many posts as possible, but none of them can solve my problem.
The route:
Route::model('user', 'User');
Route::group(array('prefix' => 'admin'), function() {
Route::get('users/force-delete/{user}', array(
'as' => 'admin-users-force-delete',
'uses' => 'AdminController#handleUserForceDelete'
));
});
The html:
<li>Force Delete</li>
The handler:
public function handleUserForceDelete(User $user)
{
$username_tmp = $user->username;
$message = 'Success! User ' . $username_tmp . ' has been deleted.';
if($user->trashed())
{
$user->forceDelete();
return Redirect::action('AdminController#showUsers')->with('message', $message);
} else {
return Redirect::action('AdminController#showUsers')->with('message', 'User deletion error! Please try again!');
}
}
I tried to put delete and force-delete at the same handler, and the delete action took place but force-delete generated NotFoundHttpException. So I guess the problem is from the force-delete action??
I solved it!
For anyone with the same trouble, soft deleted user(or anything) will not generate an instance passed to the handler (or closure). Therefore, for this case I manually create an instance.
So instead of using this:
//will not handle soft deleted model.
Route::model('user', 'User');
Use this:
Route::bind('user', function($value, $route)
{
return User::withTrashed()->where('id', '=', $value)->first();
});

Categories