Diego Utreras
Diego Utreras

Reputation: 111

Can't access data from the Users table from a function in controller

I'm trying to use a function to soft delete 2 rows in a database, one is from a table I made called persona and the other one is from the users table that laravel makes with Auth, My users table have a foreign key associated to the persona table called idPersona. What I'm trying to do is to soft delete the row from the persona table that matches the id parameter and after that soft delete the row in users where the attribute idPersona matches the id parameter that the function recieved.

I'm going to post the Controller function code

Controller function code

 public function deleteMedico($id){
        $medico = Persona::findOrFail($id);
        $medico->estado =False;
        $personaID = $medico->id;
        $user= new User();
        $user->where('idPersona',$personaID);
        var_dump($user);
        
    }

I'm going to try to explain what I'm trying to do with this controller, I use the findOrFail function to find the row I'm trying to self delete from the persona table, after I found it I set estado to false in this way soft deleting the row. After that I try to get an User instance, look for the users table where idPersona matches the id of the row that was soft deleted.

The code for self deleting it would be almost the same than with the persona table but the problem is I can't find the row in the users table, gonna post the var_dump I get of $user.

var_dump of $users

Also gonna post how my database looks in case it is useful

Database diagram

I have no idea what I need to do to get the row of the users table where the idPersona attribute matches the id attribute from the personas table. I'm new in Laravel so sorry if this question is repetitive or is nothing to hard. p

Upvotes: 0

Views: 251

Answers (2)

IGP
IGP

Reputation: 15859

Your syntax is wrong.

// $user = new User();
// $user->where('idPersona',$personaID);
$user = User::where('idPersona', $personaID)->firstOrFail();

This should fix the syntax but there are simpler ways to do this in your code.


Route model binding

Route::get('deleteMedico/{persona}', ...);

Eloquent Relationships

// Persona.php
public function user()
{
    return $this->hasOne(User::class, 'idPersona');
}
public function deleteMedico(Persona $persona)
{
     $persona->fill(['estado' => false])->save();
     $persona->user->fill(['estado' => false])->save();
}

Upvotes: 1

Izayoo
Izayoo

Reputation: 21

You forgot the get method.

User::where('idPersona',$personaID)->get();

Upvotes: 1

Related Questions