Filter results by logged-in user id

Asked

Viewed 3,795 times

0

I am building a system using the Laravel framework (I have little knowledge in Fw) and I need to get the id of the user who logged in to make the queries based on the user id.

Ex: User => lists all products registered with user id.

How can I do that?

4 answers

1


You can also use the Hasmany relation in the user model, considering that you have in the table products the key of the user (usuario_id)

class Usuario extends Eloquent{
  public function produtos(){
    return $this->HasMany('Produto');
  } 
}

class Produto extends Eloquent{
    public function usuario(){
        return $this->belongsTo('Usuario')
    }
}

and in consultation you can do:

if(Auth::check()){ //se tem usuario logado
    $usuario_produtos = Auth()->user()->produtos();
}

0

0

You can use Auth to catch the user who has logged on to the system:

if (Auth::check()){ //verifica se tem usuario logado
    $usuario_id = Auth::user()->id;
    $usuario_produtos  =  Produto::where('usuario_id', $usuario_id);
}

0

with Laravel to be able to pick up the user from the library.

use Illuminate\Support\Facades\Auth;
use App\User;

example of code

$file = DB::table('nomdatabela')
                    ->where('name', 'like',  "%" . $_nome)
                    ->where(function($query){
                        $Users = Auth::tabelausuarios()->nome;                        
                        return $query->where('nome', 'like',  "%" . $Users)
                        ->pluck('name');                        
                            }                        
                        )
                    ->get();    

Browser other questions tagged

You are not signed in. Login or sign up in order to post.