Laravel Client Switching Functionality - laravel

I am new to laravel and do not have much experience with using ORM. I am building a system in which I need build functionality to allow user to switch clients with another user. I am not sure what is the best method to achieve this.
Currently client belongs to user, do I need another association for client and user model using different foreign key ?
public function clients()
{
return $this->hasMany('App\Client');
}
public function user()
{
return $this->belongsTo('App\User');
}
Even though a client can only have one user switch request I would like to track all the requests so for example if user A makes request to switch client Test with user B and then make another request to switch the same client with user C I would like to soft delete the first record and create new record for new request. Once the other user accepts the request we change the primary key for client Test in the clients table. Will this be a One To Many / Many To Many relationship ?
What table naming conventions do I need to follow ? Any help will be much appreciated.

If I understand you correctly, you would like to temporarily switch clients for one user to another. What you should do is have another table say switched-clients that holds records for the switches with columns user1 and user2. When you want to retrieve clients, your controller checks this table first and if the record exists where('user1', 'user A') (according to your example), then you retrieve the clients for user2.

Related

Send a notification whenever any update happens in LARAVEL

Actually I am facing a problem. I need to send a notification to the admin whenever any update happens in any modal, in any user, and in any table.
To clarify more :
I have a client, a company, and an employee.
Under each part, I have many tables ( e.g: under client I have client's profile table, under company I have many tables corresponding to company's lawyer, company's files, etc.., similarly to the employee)
So correspondingly , I have many controllers thus many update methods.
So In order to send a notification to the admin whenever any update happens in any situation under any user. It's too annoying that I must include the notify statement $admin->notify(new UpdateIsMade()); under ALL update METHODS!
It's kind of redundancy.
What I want to actually approach is to find a solution that let me automatically send a notification to the admin whenever any update happens by any user under any table.
I tried to make a middleware function and tried to send a notification whenever any update happens under the client user (kind of sampling) :
public function handle(Request $request, Closure $next)
{
$clients = \App\Client::all();
foreach ($clients as $client) {
if($client->user->wasChanged()){
$arr_of_changes = $client->user->getChanges();
$admin=User::where('profile_type' , 'App\Admin')->first();
$admin->notify(new UpdateIsMade($arr_of_changes,$original_arr));
}
}
return $next($request);
}
Unfortunately this middleware didn't work.
I guess the problem is that $client->user->wasChanged() is not giving a true value whenever an update happens. It looks like wasChanged only works after the save process in the update method.
Any suggestion for my problem? Thank you for your time and sorry for the long text!
It might be less of a headache if you consider using database triggers so monitoring changes is completely separate.
You could create a new table called "change_log" with fields "action" and "created_at" then set up the trigger to insert a new record upon update of any tables you want to monitor.
Then you just set up a CRON to run at intervals that would call a Laravel controller to query the change_log and see if there are any records in it. If there are, the code would take the appropriate action to send an alert then empty the table. The change_log would remain empty until the DB trigger fires due to changes made.

Handle model dependencies in Laravel Repository Pattern

I'm discovering the Repository Pattern for my Laravel project but I have to say that I'm a bit lost once a model has several dependencies and the examples on the web are always basic and don't answer the question for more complex use cases.
Let's imagine a user on my app. He can have badges, he has different things on the app that will be slightly modified when he first performs the action (when he first sees the comments, I tell him once the different things he can do, etc), he has several "counters" to record the number of comments he made, the number of friends he invited, without having to count each entry each time.
My database looks like this:
users table:
id
pseudo
name
password
...
badges table:
user_id
badge1_xxxxxx
badge2_xxxxxx
...
I have a very limited number of badges so I decided to create a column for each of them and as soon as a user wins a badge, I get his entry (in OneToOne relationship) and I indicate that the badge in question has been won.
onboarding table:
user_id
seen_comments (boolean)
seen_results (boolean)
...
As you can see, I store each action I'd like the user to do in different columns and as soon as he has done one and I've been able to modify my app accordingly (by showing him an arrow, etc), I put the column in question to true.
user_counters table:
user_id
count_comments
count_invited_friends
...
I don't consider a user to be a user if he doesn't have an entry in each of the tables (I could have done everything in one table but the users table seemed to me to become huge). The only relationship used is OneToOne between the user and the table in question.
Should I do this ?
class UserRepository {
public function register($data) {
// Create the user
$user = User::create($data);
// Create all its dependencies which are required if I want to consider the user as fully registered in my DB
$user->badges()->create();
$user->onboarding()->create();
$user->counter()->create();
// Return the user
return $user;
}
}
Or should I create a Repository for each of these elements and create the entire user in a UserService ?
How far should I separate things and when does it become overkill?
Is there something that I don't understand in concept of Repository ? If so, could you give me some links that you found useful because I feel like I ran out of ideas for search keywords.
Thanks

Testing Laravel Eloquent Relationship

I'd like to know what's the best approach to ensure that my Activity model belongs to a User.
Activity.php
...
public function user()
{
return $this->belongsTo(User::class);
}
How can I write a test that ensure that the Activity model has that relationship?
There is no problem in testing eloquent with the database as source of truth, so you can use the database like sqlite, for speed performances.
To test it create user with the factory and then create an activity attach it to the created user after that load the activity and test if it's linked with the created user.
We are following the pattern of Given, When, Then => Given you have u user When he create an activity (logged in, create a post ...) Then check if the created activity belongs to the given user ;)

Storing remember_token to a separate table than users?

is it possible to set another table & column to store my remember tokens? I know that the framework tries to automatically find a remember_token column in my "users" model, but I want to store it separately from users. Is there a way to configure my default tokens table? Thank you
P.S - I'm using laravel 5
First, you need to create separate model for storing remember tokens and define a relationship on your User model like so
public function rememberToken() {
return $this->hasOne('RememberToken');
}
Then you need to override methods on your User model, originally defined in Authenticatable trait. Override getRememberToken() and setRememberToken() methods. You will also need to override getRememberTokenName() as it is used in where clause in EloquentUserProvider::retrieveByToken() see EloquentUserProvider line 60. In order for this to work properly you probably have to add global scope to your User model to join remember_tokens table on every query, and return 'remember_tokens.token' from getRememberTokenName() method.
Think twice as it seems more trouble than it is worth. Why would you want to store your tokens separately anyway?
I believe the way Laravel works uses a seperate column in the users table to store a single remember_me token. From my understanding it seems that logging out resets this token regardless of storing the token in a cookie (correct me if I'm wrong).
https://github.com/laravel/ideas/issues/971
If you log in with remember_me checked on your personal computer,
then again on your phone,
and maybe again with any other device,
then finally the act of signing out on any device using the remember_me token or not will reset this token in the DB.
If Laravel had a separate table, able to remember each device, it might solve the problem.

RESTful API - validation of related records

I implementing RESTful API service and i have a question about saving related records.
For example i have users table and related user_emails table. User emails should be unique.
On client side i have a form with user data fields and a number of user_email fields (user can add any number of fields independently). When the user saves the form i must first make query to create record in users table to get her ID, ​​and only then i can make query to save user emails (because in now i have id of record which come with response after saving user data). But if user enters not unique email in any field then the request will fail. So I create a record in the users table but not create record in user_emails table.
What are the approaches to implement validation of all this data before saving?
This is nor related restful api but transactional processing on the backend. If you are using Java, with JPA you can persist both element in the same transaction then you can notice if there is a problem and rollback the entire transaction returning a response.
I would condense it down to a single request, if you could. Just for performance's sake, if nothing else. Use the user_email as your key, and have the request return some sort of status result: if the user_email is unique, it'll respond with a success message. Otherwise, it'd indicate failure.
It's much better to implement that check solely on the server side and not both with the ID value unless you need to. It'll offer better performance to do that, and it'll let you change your implementation later more easily.
As for the actual code you use, since I'm not one hundred percent on what you're actually asking, you could use a MERGE if you're using SQL Server. That'd make it a bit easier to import the user's email and let the database worry about duplicates.

Resources