So I have 2 Models Users & Staff. They have one to one relationship with one another.
User.php 'hasOne' Staff
AND
Staff.php 'belongsTo' User
When I Soft Delete a User I want to soft delete Staff entry as well, I have achieved this using(Works Perfectly):
static::deleting(function ($user) {
$user->staff()->delete();
});
Now I want to restore the staff when I restore the User for that I have tried using this(Not working):
static::restoring(function ($user) {
$user->staff()->restore();
});
But this is not working. The User Entry is deleted but the Staff entry still remains soft deleted.
Can someone help me understand what I am doing wrong here?
Also, Is this the best way to get this done? Or is there some other way this should be done?
PS: I'm using Laravel 5.5
It isn't working because $user->staff() doesn't fetch deleted staff. That's how relationships work by default.
Just replace it with this:
static::restoring(function ($user) {
$user->staff()->withTrashed()->restore();
});
"static::restoring" event is never triggered when restoring a batch of models.
If you're doing something like:
Yourmodel::whereIn('id', [1,2,3])->restore();
It will restore your models but "static::restoring or restored" will never be triggered, instead you could do something like this:
$models = Yourmodel::whereIn('id', [1,2,3])->get();
foreach($models as $model) {
$model->restore();
}
Related
I have used SoftDelete to delete an event from events table. SoftDelete is working fine. I have shown that SoftDelete event withTrashed() in view and it showing. Now i want to edit that SoftDelete event data without restore it. Is it possible?
I am getting an error 400 - we could not find the page when i have tried it.
$data['events'] = $qBuilder->EventComplete()->withTrashed()
->orderBy('events.event_date', 'desc')
->groupBy('events.id')
->paginate(AppHelper::getConfigValue('ADMIN-PAGINATION-LIMIT'));
It should be possible like this:
Model::withTrashed()->find(5)->update(['attribute' => 'value']);
so you are using eloquent apply withTrashed - find single model (here with id = 5) and then you update attributes you want.
You haven't showed more but, but in your case assuming you use Route model binding you might need to adjust it to allow to find also soft deleted models:
Route::bind('user', function ($value) {
return App\User::withTrashed()->findOrFail($value);
});
So I'm starting my path on the front end development. I have a table with user description and a button that changes the state of the user. Everything except a validation works fine, the state is being changed and the page is refreshed correctly. Here is my code...
public function changeState(Request $request)
{
if($request->ajax()){
$usernames = Input::get('usernameSend');
if(isset($usernames)){
$user = User::Where('username', '=', $usernames);
if ( !$user->get() ){
Log::warning("User not found.");
} else {
if(!$user->get()->isEmpty()) { // verify if the user is active
$user->delete(); //soft delete the given user
}else{
$user->restore(); //removes the soft delete for the given user
}
}
}else{
Log::warning("Username doesn't exist on database.");
}
}
}
I'll explain what I find important on my logic
if(isset($usernames)) -> verify if the username sent through the AJAX request is valid
if ( !$user->get() ) -> verify if the user is on the database
(!$user->get()->isEmpty()) -> verify if the user is soft deleted
I eventually want to add a function where one administrator can destroy a entry and although this works fine this way, the page is refresh and the user is vanished I think I should warn the user that the state wasn't changed and the user wasn't found in the database. But the if ( !$user->get() ) is ignored even if I delete the user from the database manually and then run the script...been searching on the Database API but found nothing. What am I doing wrong?
TIA
Edit: To clarify a bit more here are some images to exemplify
The user is in the dabatase(working as intended)
I removed the user from the database(database is ordered by ID)
Still the same result(not working as intended)
When I refresh the page the entry is gone(what shows that I'm actually removing the entry from the database)
From Laravel soft deleting
In addition to actually removing records from your database, Eloquent can also "soft delete" models. When models are soft deleted, they are not actually removed from your database. Instead, a deleted_at attribute is set on the model and inserted into the database. If a model has a non-null deleted_at value, the model has been soft deleted. To enable soft deletes for a model, use the Illuminate\Database\Eloquent\SoftDeletes trait on the model.
Your user model must contain the SoftDeletes trait, such as:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class User extends Model
{
use SoftDeletes;
// ...
To check whether a user is soft deleted, use the trashed method:
<?php
$users = App\User::withTrashed()->get();
foreach ($users as $user) {
if ($user->trashed()) {
// this user is soft deleted
} else {
// this user is not deleted
}
}
Anything not in $users has been hard deleted.
You can restore any soft deleted record by doing:
$user->restore();
You need to use withTrashed if you want to restore from deleted records(soft).
Use this in
User::withTrashed()->Where('username', '=', $usernames)->restore();
I am using backpack to created admin panel in my project. I have two types of user one is Superadmin and second is admin. I just wanted to give the permissions to superadmin as he can list,add,edit all the rows from database..
but the admin can only edit,delete and list those rows created by himself..
So please help me, I am new in laravel backpack??
Filter the results you show in the setup() method of your entity's CrudController, then disallow access to update/destroy methods.
You result could look something like this:
public function setup()
{
// take care of LIST operations
if (\Auth::user()->hasRole('admin')) {
$this->crud->addClause('where', 'author_id', '=', \Auth::user()->id);
}
}
Additionally, you need to place checks inside your update() and destroy() methods, to not allow an admin to delete someone else's entry.
// place this both inside your update() and inside your destroy() method
if (\Auth::user()->hasRole('admin') && $this->crud->entry->author_id!=\Auth::user()->id) {
abort(405);
}
Hope it helps.
I'm working in a Webapp and I have a problems to work with a intermediate table, these are my tables in mysql:
User:
Integer:id
String:name
String:email
String:phone
Exercise:
Integer:id
String:name
String:description
User_Exercise:
Integer:id
Integer:id_user
Integer:id_exercise
Integer:record
So, what I want to do is that when I create an exercise, it be created one row for each user with the exercise-id that I have created it before. Later the user could change his record in this exercise.
I have thought to create a model to handle the user_exercise's table but I don't know if there is some way to do this better or not.
So, There are some way to do this without create a new model?
PD: Sorry for my terrible english
You don't need a seperate model for User_Exercise
You can use $this->belongsToMany from base Model i.e., User
Note :
For insert process you can get the parent id by
$insertUser = User::create($userData);
then
$insertUser->id for taking the last insert id
And then to retrieve with respect to User_Exercise you shall use $this->belongsToMany from your User Model
Example
Have this in your User Model
public function getUser() {
return $this->belongsToMany('App\User', 'excercise_name', 'user_id', 'excercise_id')->select(array('exercise.id', 'excercise.name'));
}
And Get the data you need from any Controller like this
$userData = User::find($userId)->getUser;
I'm asking this question in order to find the best practice to do it.
DB::table('owners')
->where('property_id',$id)
->update(array('person_id'=>$owner));
The problem is that in the table owners might not have a row to update. In that occasion i need to make an INSERT INTO instead of UPDATE.
My problem is that i have to run 2 queries each time, one for checking if the row already exists, and one more to update or insert into. Is it right to run 2 queries each time? Is there a better way to achieve that? I need to keep the queering processes fast for the user.
UPDATE: The table owners is a middle table of a many to many relationship. Unfortunately i cannot use ON DUPLICATE KEY.
well you could try to use firstOrCreate method of Laravel to check if user exists. After that retrieve the user object and pass it to an update function else if the user is not found firstOrCreate method will take care of you as it will create a new user with the data you will provide and will auto increment last user + 1 id.
There is also the option to use firstOrNew which will check if an instance exists based on the array values you passed and if no match is found it will auto create a new instance of the model you are handling for further manipulation.
Here is example with firstOrNew
Example Controller file.
public function getFirstUserOrNew($email)
{
$user = User::firstOrNew(['email' => $email]);
if($user)
{
$this->UpdateUser($user);
}
else
{
$this->CreateUser($user);
}
}
public function UpdateUser(User $user)
{
//Do update stuff
}
public function CreateUser(User $user)
{
//Do create stuff
}
P.S - I'm from Greece, if you want to discuss anything in native language send me a PM :)
EDIT:
Thanks to #Pyton contribution It seems you can also use an updateOrCreate method as it is explained here.
If you want to Update or Insert row You can use updateOrCreate
$owner = Owner::updateOrCreate(['property_id' => $id], ['person_id'=>$owner]);