Dec 30, 2021
10
Level 1
implement a Log System in Laravel
Hi guys!
I want to implement a logging system for my Laravel project
is this Method is clean and true? Do you have a better solution?
and here is my controller:
public function store(Request $request)
{
$image = $request->image->store('products');
// create the post
Products::create([
'title' => $request->title,
'price' => $request->price,
'image' =>$image,
]);
$success_create_status="post created successfully!";
//create success log
$data=[
'status'=>$success_create_status
];
DB::table('logs')->insert($data);
return redirect(route('products.index'));
}
and log migration:
public function up()
{
Schema::create('logs', function (Blueprint $table) {
$table->id();
$table->string('status');
$table->timestamps();
});
}
Level 102
@mehrabt No worries
Make a table like this
Schema::create('logs', function (Blueprint $table) {
$table->id();
$table->string('message');
$table->timestamps();
});
and a model called Log
On the Post model add this
protected static function booted()
{
static::created(function ($post) {
$userId = auth()->id();
$postId = $post->id;
\App\Models\Log::create([
'message' => "User $userId created a new post: $postId",
]);
});
}
1 like
Please or to participate in this conversation.