This package needs PHP 8.1+ and Laravel 9.0 or higher. The latest version of this package needs PHP 8.2+ and Laravel 8 or higher. If you're employing an older version of the Laravel framework, Then you can utilize v3, v2, or v1 of this package. Installation and Setup For the installation purpose, you've to run this command:
composer require spatie/laravel-activitylogThe service provider will be automatically registered. If you need to store your activities in another database connection, you can specify ACTIVITY_LOGGER_DB_CONNECTION in your .env file. After that, you've to clear the application config cache:php artisan config:clearYou've to publish the migration with this command:php artisan vendor:publish --provider="Spatie\Activitylog\ActivitylogServiceProvider" --tag="activitylog-migrations"Next, you've to generate the activity_log table by using this command:php artisan migrateUsage Here's an example of how you can log some activity:activity()->log('Hey, I logged something');It will generate a record in the activity_log table. You can recover all activity utilizing the Spatie\Activitylog\Models\Activity model handed by the laravel-activitylog package.Activity::all();Here's another advanced way of doing this:activity() ->performedOn($anEloquentModel) ->causedBy($user) ->withProperties(['customProperty' => 'customValue']) ->log('Look mum, I logged something');$lastLoggedActivity = Activity::all()->last();$lastLoggedActivity->subject; //returns an instance of an eloquent model$lastLoggedActivity->causer; //returns an instance of your user model$lastLoggedActivity->getExtraProperty('customProperty'); //returns 'customValue'$lastLoggedActivity->description; //returns 'Look mum, I logged something'Automatic model event logging This package is pretty cool, it can also automatically log model events. For Example:$newsItem->name = 'updated name';$newsItem->save();//updating the newsItem will induce an activity being logged$activity = Activity::all()->last();$activity->description; //returns 'updated'$activity->subject; //returns the instance of NewsItem that was generatedWhen you Call $activity->changes. It will return the following array:['attributes' => ['name' => 'original name','text' => 'Lorum Ipsum', ],'old' => ['name' => 'updated name','text' => 'Lorum Ipsum', ],]; Other Or
By running the previous command, the activitilog.php file will be created where we can find different activity log Laravel configuration parameters. There are already several predefined parameters that can be very useful such as:
enabled – If set to false, no activities will be saved to the database. – This can be very useful if we want to disable the logging mechanism, for example in our local environment.
delete_records_older_than_days – a parameter used to automatically clean up older activity logs Laravel.
table_name – a parameter used to specify the activity Laravel log table – By default, this is set to activity_log
…
We can modify these parameters as we need or add additional based on the functionality we are building.
3 LOGGING MODEL EVENTS
Laravel activity log package can automatically log events such as a Laravel model log that is created, updated or deleted. In our User.php model, we will use the Spatie LogsActivity trait. This trait is extremely simple and has the static boot function for any model, as well as for registering an event that we described. For each event, the related query is performed and it is logged inside the database.
In our model we can set what attributes we will be logging by using:
If our model contains attributes that we want to ignore on a trigger change, we can use:
By default, this logger is configured to log every attribute of the model, but there is an easy way to change that. We can log only the changed attributes after the update by using the following configuration:
Customizing the events being logged
By default, the package will log the created, updated, deleted events, but we can customize with:
Customizing the description:
By setting the all attributes our User model looks like:
Our Laravel activity log installation, setup, and logging model events are completed and we can test it by creating, updating or deleting a user in our application.
Create a user:
activity_log table:
Update user:
activity_log table:
4 RECORDING LOGIN INFORMATION OF THE USERS
As we have already mentioned before, there are pre-defined Spatie logging events that are out of the box with this package. However, sometimes we want to log data on successful login or log out of the users in our application. This is also possible and easy to achieve and we need to follow the following steps:
Create an Event Listener
Map the Event Listener to the EventServiceProvider
4.1 Create an Event Listener
For creating an Event Listener, we need to run the following command:
After the new Event Listener is created, insert the following code into the LoginSuccessful listener:
As we can see from the code above, we are going to simply provide the subject and the description of the Laravel log activity, and after that, we will simply flush the success message to the end-user and store the data into the activity_log table.
4.2 Map the Listener
Once we created the listener, we should attach it to the EventServiceProvider.php file.
Now we can record all login activity of the user in the log activity Laravel table. When the user will login into the application a new record will be created in our table.
So, if you want to grow even more, don’t hesitate to watch a Spatie activity log tutorial again and again or any spatie/laravel-activitylog example to improve continuously.
On 8th February 2022,Laravel 9has been officially released. According to the official website. With this major version release, developers will get 1 year of bug fixes support and 2 years of security updates from the laravel team. Laravel 9 comes with various interesting features and overall improvement of the core framework. Let's find out what's new in Laravel 9.
At a glance Laravel 9
Version
Laravel 9
Release Date
8th Feb 2022
Bug fixes
Until Feb 8, 2023
Security fixes
Until Feb 8, 2024
Minimum PHP
version 8
Laravel 9 new features
Laravel 9 required a minimum PHP version 8. New features are Controller route group, Accessors / Mutators improvement, Flysystem 3.x, Eloquent Enum casting, Inline blade templating, Full-text indexing, Enums implicit route binding, newly designed route listing, testing coverage option, new query builder interface, PHP 8 string function included, anonymous stub migrations, SwiftMailer to Symfony mailer and many interesting features. Let's discover these features.
Controller Route Group
From laravel 9 we can use common routes as controller group routes which will make route defining more easy and readable. Let's take a look at what it looks like.
use App\Http\Controllers\PostController;
Route::controller(PostController::class)->group(function () {
Route::get('/posts/{id}', 'show');
Route::post('/posts', 'store');
});
The server.php file
The server.php file used for php artisan serve. From laravel 9, it will be removed from the root of the project. This will be included from the inside of the framework.
Inline Blade Templating
With laravel 9, we can convert any blade template string to valid HTML tags easily with the help of an inline blade template. Here an example is given below.
use Illuminate\Support\Facades\Blade;
return Blade::render('Hi, {{$name}}', ['name' => 'Jhon']);
Flysystem 3.x
In Laravel 9, the storage facade will use the Flysystem 3.
Anonymous Stub Migrations
To prevent migration class name collisions we can use anonymous stub migration features in laravel 9. Laravel 9 will use this feature as default for the command php artisan make:migration
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration {
public function up()
{
Schema::table('people', function (Blueprint $table) {
$table->string('name')->nullable();
});
}
};
Accessors / Mutators Improvement
From laravel 9, we can easily define eloquent model accessors and mutators every easily with sort syntax which is a very intuitive syntax.
Before laravel 9
public function getNameAttribute($value)
{
return strtoupper($value);
}
public function setNameAttribute($value)
{
$this->attributes['name'] = $value;
}
In laravel 9
use Illuminate\Database\Eloquent\Casts\Attribute;
public function name(): Attribute
{
return new Attribute(
get: fn ($value) => strtoupper($value),
set: fn ($value) => $value,
);
}
Enum Eloquent Attribute Casting
Like an as eloquent date, number and other types. Now we can cast eloquent attributes to Enum.
use App\Enums\PostStatus;
protected $casts = [
'status' => PostStatus::class,
];
Full-Text Indexes
In a table definition, we can use full-text indexes in laravel 9.
Laravel 9 included bootstrap 5 pagination view. To use bootstrap 5 pagination view add this line in your app service provider inside the boot method.
use Illuminate\Pagination\Paginator;
public function boot()
{
Paginator::useBootstrapFive();
}
Functions and New Helpers
The \Illuminate\Support\Str facade will use PHP 8 string function internally for str_contains, str_starts_with and str_ends_with
Helper
str('Laravel')->append(' Article');
// 'Laravel Article'
str()->snake('LaravelArticle');
//laravel_article
//HTTP redirect to a name route
return to_route('posts.show', ['post' => 1]);
Query Builder Interface
Laravel 9 introduce a new query builder interface.
return Model::query()
->whereNotExists(function($query) {
// $query is a Query\Builder
})
->whereHas('relation', function($query) {
// $query is an Eloquent\Builder
})
->with('relation', function($query) {
// $query is an Eloquent\Relation
});
New route list design
Laravel 9 comes with a beautiful route list design in CLI with colour highlighted HTTP verb. We'll see the defined route list with the command php artisan route:list
New Test Coverage
A new test coverage option was added in Laravel 9. You will get the test coverage by artisan command artisan test --coverage. Here is the sample output.
Laravel celebrated its 10th-anniversary last year. Today it is the most popular PHP framework used by thousands of developers. The ecosystem around Laravel is huge, and new trends are constantly popping up. This survey attempts to gain insight into the representation of this outstanding community's diverse technologies and behaviors.
Each year Tobias Petry leads a community effort to collect information on the state of the Laravel community by running a survey. It is an effort to gain insights into where we are as a community so that we might understand where we are. It is not something backed by a major corporation, nor is it something that collects the data to sell. Instead, it is a simple way for us as the Laravel community to understand where we are - and how we might be able to move forward. Where the trends are leaning and how we might react to that.
It is a fantastic initiative with honest intention and insights that we as a community need. Let's have a look through the statistics for last year to understand where we are coming from:
Various statistics were gathered from this survey, from location to gender and team size - all of which are interesting statistics. But I am going to focus on a few specifics for this article.
The years of programming experience is interesting, and we have the majority of submissions sitting between 2 and 10 years - with 10-20 years leading closely behind. I wonder how much this will change this year?
Let's compare this to their Laravel experience:
So the trend here is around what you would expect. Many developers with 2-5 years of experience are using Laravel, which is very similar to the years of programming experience. The reason we have nothing over ten years is due to Laravels age. You can see the point in people's careers that Laravel came out - and the impact it has had on people adopting it.
Let's compare the usage of different PHP versions people are using next.
It is good to see this statistic leaning this way. More and more people moving their PHP versions forward is a massive step for the PHP community as a whole. As our language progresses, we are becoming more strict on standards and patching, and this chart shows that nicely. There will always be legacy projects that are impossible to upgrade, or the client doesn't have the budget. But the trend is leaning towards the newer and better versions of our beloved language.
Code editors is another interesting one. What are people using to write their code on a day-to-day basis?
Leading the charge is PhpStorm. It is a fantastic product, and it is good to see so many in the community investing in quality tools. Coming in a close second is VS Code, which is getting better and better with each release - and with the right configuration, it can behave almost as well as PhpStorm. Will this year change at all? How about next year with the price increase of the licensing for PhpStorm?
Lastly, let's look at the Operating System usage.
This is pretty well balanced, and you can see the effect of development tooling being focused around the Mac in the Laravel community having a big impact here. It isn't a huge difference between the main competitors - and I am very interested to see what the 0.18% use 👀
So as you can see, the stats aren't anything that will change your mind - but looking through them, we can understand where our fellow developers are, giving us an insight into our market. We have a highly saturated mid-senior level running on PHP 8 and 7.4, mainly using macOS. The most significant amount of contributions for last year did come from Europe, but the creator of the survey is from this continent, so perhaps it is an inadequate representation for everywhere.
Let's see what we can do this year? Perhaps we can start seeing more submissions from the US and Eastern Europe as well as Australia and Asia? Hopefully, we will see the gender split level out more thanks to the fantastic work of communities such as Larabelles.
You can contribute to this year's survey here, and help get more insights into the community.