No data displayed to the frontend from observer - Laravel - laravel

I want to output user activity history.
Here's observer that i want to output message of user activity to my front end if($drop_student){ Logger::createLog("Student Schedule Removed for ". $student->first_name . " " . $student->last_name . " '" . $schedule->name . "'");
UPDATED
public function created(StudentSchedule $student_schedule)
{
$student = $student_schedule->student()->get()->first();
$schedule = $student_schedule->schedule()->get()->first()->subject->subject;
Logger::createLog("Student Schedule Added for " . $student->first_name . " " . $student->last_name . " '" . $schedule->name . "'");
}
/**
* Handle the student schedule "updated" event.
*
* #param \App\Models\Student\Schedule $student_schedule
* #return void
*/
public function updated(StudentSchedule $student_schedule)
{
$student = $student_schedule->student()->get()->first();
$schedule = $student_schedule->schedule()->get()->first()->subject->subject;
$drop_students = $student_schedule->schedule()->where('id')->get();
foreach ($drop_students as $drop_student) {
$drop_student = $student_schedule->schedule();
}
$drop_student->save(['final_grade' => 'DRP']);
if ($drop_student) {
Logger::createLog("Student Schedule Removed for " . $student->first_name . " " . $student->last_name . " '" . $schedule->name . "'");
} else {
Logger::createLog("Student Schedule Updated for " . $student->first_name . " " . $student->last_name . " '" . $schedule->name . "'");
}
}
Here my relationship models
student & schedule hasMany student schedule
student schedule model:
class Schedule extends Model
{
use HasFactory;
protected $table = 'student.schedules';
protected $fillable = [
'student_id',
'schedule_id',
'removal_grade',
'final_grade',
'is_published',
];
public $timestamps = false;
public function student()
{
return $this->belongsTo('App\Models\Student', 'student_id');
}
public function schedule()
{
return $this->belongsTo('App\Models\Schedule', 'schedule_id');
}
}
student model:
class Student extends Model
{
use HasFactory;
const MALE = 'male';
const FEMALE = 'female';
protected $table = 'students';
protected $fillable = [
'first_name',
'last_name',
'middle_name',
'suffix',
'email',
'student_number',
'sex',
'birthdate',
'lrn',
"profile_picture"
];
protected $appends = ['allow_delete'];
public function schedules()
{
return $this->hasMany('App\Models\Student\Schedule', 'student_id', 'id');
}
}
schedule model:
class Schedule extends Model
{
use HasFactory;
const MONDAY = 'M';
const TUESDAY = 'T';
const WEDNESDAY = 'W';
const THURSDAY = 'TH';
const FRIDAY = 'F';
const SATURDAY = 'S';
const SUNDAY = 'SUN';
protected $table = 'schedules';
protected $fillable = [
'start_time',
'end_time',
'room_id',
'subject_id',
'session_id',
'user_id',
'day',
'section_id',
'price_per_unit_id',
];
protected $casts = ['day' => 'array'];
protected $appends = ['allow_delete', 'enrollments_count'];
public function students()
{
return $this->hasManyThrough(
'App\Models\Student',
'App\Models\Student\Schedule',
'schedule_id',
'id',
'id',
'student_id',
);
}
public function studentSchedules()
{
return $this->hasMany('App\Models\Student\Schedule', 'schedule_id', 'id');
}
}
Here's api that i use.
Route::post('/drop-schedules', [EnrollmentController::class, 'dropSchedules']);
Here's dropSchedules method in controller.
public function dropSchedules(Request $request)
{
StudentSchedule::whereIn('id', $request->student_schedules)->update(['final_grade' => 'DRP']);
return response()->json([
'message' => 'Student schedules successfully dropped.'
], 200);
}
but when i fire the drop schedule button. This logic it doesn't run. Only the created method Student Schedule Added for

Related

multiple images not storing in database

I am trying to upload multiple images on database but its not storing. when I var_dump the data I see the images but it's not storing in database.
the code for store the data is---
$ad = AdList::create([
"userId" => $userId,
"adTitle" => $request->data['title'],
"photos" => json_encode($imageList),
]);
var_dump($ad);
And the I got after var_dump is---
["photos"]=>
string(51) "["dodo (1)_1668406861.webp","dodo_1668406862.webp"]"
what is the reason for not storing in database? I am using laravel & vue
Ad_list model---
class AdList extends Model
{
use HasFactory, Sluggable;
protected $guarded = [];
// public $incrementing = false;
// protected $table = 'ad_lists';
// protected $keyType = 'string';
public function user(){
return $this->belongsTo(User::class, 'userId','id');
}
public function category(){
return $this->belongsTo(Category::class, 'catId','id');
}
public function subcategory(){
return $this->belongsTo(Category::class, 'subCatId','id');
}
public function businessPage(){
return $this->belongsTo(BusinessPage::class, 'userId','userId');
}
/**
* Return the sluggable configuration array for this model.
*
* #return array
*/
public function sluggable(): array
{
return [
'url' => [
'source' => 'title'
]
];
}
}
Maybe your table is not connected to your model. Try to add this:
protected $table
class AdList extends Model
{
use HasFactory;
use Uuid;
public $incrementing = false;
protected $table = 'adlist_table';
protected $keyType = 'string';
protected $guarded = [];
}
Try to add protected $table = ''adlist_table" in your model;

How to get nested relation record for ajax request in laravel?

I have Model Ticket in which user explain issue.
Ticket.php
class Ticket extends Model
{
protected $table = 'tickets';
/**
* #var array
*/
protected $guarded = [];
/**
* #var array
*/
protected $hidden = [
'created_at', 'updated_at'
];
public function ticket_replies()
{
return $this->hasMany(TicketReply::class, 'ticket_id');
}
public function ticket_assigned_agents()
{
return $this->hasMany(TicketAssignedAgent::class, 'ticket_id');
}
}
There is another model
TicketReply.php
class TicketReply extends Model
{
protected $table = 'ticket_replies';
/**
* #var array
*/
protected $guarded = [];
/**
* #var array
*/
protected $hidden = [
'created_at', 'updated_at'
];
public function staffs(){
return $this->belongsTo(Staff::class,'user_id');
}
public function ticket()
{
return $this->belongsTo(Ticket::class, 'ticket_id');
}
}
Now I want to get staff name from ticket reply
Query
public function getReplies($ticket_id)
{
$ticket = Ticket::where('id',$ticket_id)->with('ticket_replies')->first();
return response()->json($ticket);
}
I want to get staff name from TicketReply model in ajax success.
$.each(ticket.ticket_replies, function(index, reply) {
console.log(reply.staffs.name);
}
But it is not working. What can I do about it?
eager load the nested relationship
public function getReplies($ticket_id)
{
$ticket = Ticket::where('id',$ticket_id)->with(['ticket_replies','ticket_replies.staffs'])->first();
return response()->json($ticket);
}
and then do the same you are doing
$.each(ticket.ticket_replies, function(index, reply) {
console.log(reply.staffs.name);
}

Why laravel auditing not functioning?

I have done my coding but the laravel audit seems not catch the data for update.
The data i try to update is on the column of value, but on the database the value are not be catch on audit table for auditing the update changes .
below is the coding for update the data.
academicsetting.php:
class AcademicSetting extends Model implements Auditable
{
use SoftDeletes, ActiveScope;
use \OwenIt\Auditing\Auditable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $dates = ['deleted_at'];
protected $fillable = [
'id',
'type',
'field',
'name',
'value',
'description',
'is_active',
'created_by',
'created_at',
'updated_by',
'updated_at',
'deleted_by',
'deleted_at',
];
protected $casts = [
'value' => 'json',
];
public function transformAudit(array $data): array
{
dump($data);exit();
if ($data['event'] == 'created') {
$data['new_values']['created_by'] = Staff::where('id', $this->getAttribute('created_by'))->value('name');
$data['new_values']['updated_by'] = Staff::where('id', $this->getAttribute('updated_by'))->value('name');
}
if ($data['event'] == 'deleted') {
$data['old_values']['deleted_by'] = Staff::where('id', $this->getOriginal('deleted_by'))->value('name');
$data['new_values']['deleted_by'] = Staff::where('id', $this->getAttribute('deleted_by'))->value('name');
}
if ($data['event'] == 'updated') {
$data['old_values']['updated_by'] = Staff::where('id', $this->getOriginal('updated_by'))->value('name');
$data['new_values']['updated_by'] = Staff::where('id', $this->getAttribute('updated_by'))->value('name');
}
return $data;
}
}
academicgeneralcontroller.php:
public function update(Request $request, $id)
{
/** implode multi dropdown value */
$request['final_attendance_reset_mark'] = $request->input('final_attendance_reset_mark');
/** end */
$this->general->update($request->except('_token', 'academicsetting-table_length', '_method'), $id);
Session::flash('alert-success', msg('msg_success_update'));
return redirect()->route('academic_general.index');
}
generalrepository.php:
class GeneralRepository extends Repository
{
/**
* Specify Model class name
*
* #return mixed
*/
public function model()
{
return AcademicSetting::class;
}
public function update(array $data, $id, $attribute = 'id')
{
// dump($data);exit();
foreach ($data as $key => $value) {
if ($key == 'final_attendance_reset_mark') {
$array = [];
if (!empty($value)) {
foreach ($value as $key_value => $value) {
$array[(int) $key_value] = (int) $value;
}
}
$json = json_encode($array, JSON_FORCE_OBJECT);
// dump($json);
$update_value = [
'value' => $json,
];
} else {
$update_value = ['value' => $value];
}
dump($update_value);exit();
$general = AcademicSetting::where('field', $key)->update($update_value);
}
}
}
Not sure if this will help but,
i see you have the following in the transform method:
$data['new_values']['created_by'] = Staff::where('id', $this->getAttribute('created_by'))->value('name');
in the documentation i see the following:
$data['old_values']['role_name'] = Role::find($this->getOriginal('role_id'))->name;
the above is to record the audit by transforming the role_id to the role_name, enabling you to capture the role_name as well.
https://laravel-auditing.herokuapp.com/docs/4.1/audit-transformation

laravel 5.4 : Image file not uploaded on the aws server

When i work on locally upload image on folder works perfect but when i try to upload image on amazon web server file not uploaded and back with same page.Is there any problem with my code ?
Here is my controller function to save data :
// CountryController
public function save(Request $request) {
try {
$file = $request->file('flag_image');
$this->validate($request, Country::rules());
//$request->validate(Country::rules());
/*Image Upload code*/
If(Input::hasFile('flag_image')){
$file = Input::file('flag_image');
$destinationPath = public_path(). '/images/admin/country/';
$filename = $file->getClientOriginalName();
$image = time().$filename;
$file->move($destinationPath, $image);
$imgpath = 'images/admin/country/'.$image;
}
if($file !="") {
$request->merge(['flag_image' => $imgpath]);
}
/*Image Upload code end*/
$country = Country::saveOrUpdate($request);
if($file !="") {
$country->flag_image = $imgpath;
$country->save();
}
if($country !== false) {
return redirect()->route('lists-country')->with('success', trans('Country data added successfully.!!'));
} else {
return back()->with('error', "Unable to save country data.!!")->withInput();
}
} catch (\Exception $ex) {
return back()->with('error', "Unable to save country data.!!")->withInput();
}
}
And my model code look like:
//country model
namespace App;
use Illuminate\Http\Request;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Input;
class Country extends Model
{
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'title',
'short_name',
'flag_image',
'status'
];
const STATUSES = [
'Active' => 'Active',
'Inactive' => 'Inactive',
];
const DEFAULT_STATUS = 'Active';
/**
* Indicates if the model should be timestamped.
*
* #var bool
*/
public $timestamps = false;
public static function rules() {
return [
'title' => 'required|string|max:255',
'short_name' => 'required',
'status' => 'required|string|in:' . implode(",", Country::STATUSES)
];
}
public static function saveOrUpdate(Request $request) {
try {
$id = $request->get('id', false);
$country = false;
DB::transaction(function () use ($request, &$country, $id) {
$country = $id ? Country::findOrFail($id) : new Country();
$country->fill($request->all());
try {
$country->save();
} catch (\Exception $ex) {
throw $ex;
}
});
return $country;
} catch (\Exception $ex) {
throw $ex;
}
} }
What's the problem i didn't find anything.

Serialization of 'Closure' is not allowed laravel Queue

I am scraping a site a get some of the data and it's a time taking job so I googled and found that Queue is good for this process I am stucked in this error
Serialization of 'Closure' is not allowed
My code:
class SiteScraper extends Job implements ShouldQueue
{
use InteractsWithQueue, SerializesModels;
protected $client;
protected $crawler;
/**
* Create a new job instance.
*
* #return void
*/
public function __construct()
{
$this->client = new Client();
$this->crawler = $this->client->request('GET', 'example.com/login/');
$form = $this->crawler->selectButton('Log In')->form();
$this->crawler = $this->client->submit($form, array('email' => 'useremail', 'pass' => 'pass'));
$this->crawler->filter('.flash-error')->each(function ($node) {
print $node->text() . "\n";
});
}
public function handle()
{
$crawler = $this->client->request('GET', $url_to_traverse);
$status_code = $this->client->getResponse()->getStatus();
if($status_code == 200){
$crawler->filter('.friendBrowserNameTitle > a')->each(function ($node) {
$names = $node->text() . '<br>';
$profileurl = $node->attr('href') . '<br>';
echo "Name : " . $names . " Profile Link : " . $profileurl;
});
}
else{
echo $status_code;
}
}
}
Any help where I am going wrong?
Only Eloquent models will be gracefully serialized and unserialized when the job is processing (Source)
So I guess that in your case, you have to write your current construct code into handle() method
class SiteScraper extends Job implements ShouldQueue
{
use InteractsWithQueue, SerializesModels;
/**
* Create a new job instance.
*
* #return void
*/
public function __construct(){ }
public function handle()
{
$client = new Client();
$crawler = $client->request('GET', 'example.com/login/');
$form = $crawler->selectButton('Log In')->form();
$crawler = $client->submit($form, array('email' => 'useremail', 'pass' => 'pass'));
$crawler->filter('.flash-error')->each(function ($node) {
print $node->text() . "\n";
});
$crawler = $client->request('GET', $url_to_traverse);
$status_code = $client->getResponse()->getStatus();
if($status_code == 200){
$crawler->filter('.friendBrowserNameTitle > a')->each(function ($node) {
$names = $node->text() . '<br>';
$profileurl = $node->attr('href') . '<br>';
echo "Name : " . $names . " Profile Link : " . $profileurl;
});
}
else{
echo $status_code;
}
}
}

Resources