How to show only the posts of the logged-in user?

Asked

Viewed 38 times

0

I have a question at the moment of showing the post user only who is logged in?

Man model:

class propuestas extends Model
{
    protected $fillable = ['titulo', 
        'descripcion', 
        'estado', 
        'linea_id', 
        'user_id'
    ];
    public function user()
    {
        return $this->belongsTo(User::class);
    }
    public function linea()
    {
        return $this->belongsTo(Lineas::class);
    }
}

Man controller:

public function propuestas_index()
{
    $this->middleware('auth');
    //$this->middleware('isroot');   
    $propuestas = Propuestas::all();
    $user = User::all();    
    $lineas = lineas::all();
    return view('tutor.propuestastutor', 
        array(
            'propuestas' => $propuestas,
            'user' => $user, 
            'lineas' => $lineas 
        ) 
    );   
}
  • related: https://answall.com/questions/148776/para-que-serve-um-scope-no-laravel/151866#151866

  • related: https://answall.com/questions/274713/como-configurar-um-anonymous-global-scopes-no-laravel/274721#274721

1 answer

0

You can define a Local Scope:

class Propuestas extends Model
{
    public function user()
    {
        return $this->belongsTo(User::class);
    }

    ...

    /**
     * @param  \Illuminate\Database\Eloquent\Builder  $query
     * @param  int                                    $id
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function scopeByUser(Builder $query, int $id)
    {
        return $query->whereHas('user', function ($user) use ($id) {
            $user->where('id', $id);
        });
    }
}

So instead of doing Propuestas::all(), just do:

$propuestas = Propuestas::byUser(Auth::id())->get();
  • I tried to implement, but even having put by the logged user is returning me worthless

  • 1

    Solved, the only thing missing was a ->get() at the end of $propuestas = Propuestas::byUser(Auth::id()). Thank you very much, it was of great help!!

Browser other questions tagged

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