How to relate two records in an elegant way?

Asked

Viewed 98 times

2

At a certain point of my application I am creating a post and relating this to the session user:

public function adicionar(CadEditPost $request)
{        
    $request->merge(['user_id' => Auth::user()->id]);

    if(Post::create($request->all()))
    {
        return redirect('/painel/posts')
                ->with(['status' => 'success', 'mensagem' => 'Post adicionado com sucesso!']);
    }

    return redirect('/painel/posts')
            ->with(['status' => 'error', 'mensagem' => 'Ocorreu um erro ao tentar adicionar o post!']);
}

Is there a more "elegant" or appropriate way to generate this relationship instead of using:

$request->merge(['user_id' => Auth::user()->id]);

Note: In the post table user_id is a Foreign which points to the table users spine id.

Would this shape be better:

Auth::user()->posts()->create($request->all());

Model User:

<?php

namespace App\Models;

use Illuminate\Notifications\Notifiable;
use App\Notifications\NotificarTrocaSenha;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    use Notifiable;

    /**
     * Código dos status existentes
     */
    const STATUS = [
        0 => 'Inativo',
        1 => 'Ativo',
        2 => 'Bloqueado',
        3 => 'Excluido'
    ];

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'password', 'sexo'
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];

    /**
     * Retorna os posts relacionados ao usuário
     * 
     * @return \Illuminate\Database\Eloquent\Relations\HasMany 
     */
    public function posts()
    {
        return $this->hasMany('App\Models\Post');
    }

    /**
     * Send the password reset notification.
     *
     * @param  string  $token
     * @return void
     */
    public function sendPasswordResetNotification($token)
    {
        $this->notify(new NotificarTrocaSenha($token));
    }

    /**
     * Traduz a sigla sexo para Feminino ou Masculino
     * 
     * @return string
     */
    public function getSexoMutatorAttribute()
    {
        return ($this->sexo == 'f') ? 'Feminino' : 'Masculino';
    }

    /**
     * Traduz a sigla status para algo compreensivo
     * 
     * @return string
     */
    public function getStatusMutatorAttribute()
    {
        $status = self::STATUS;
        return $status[$this->status];
    }
}

Model Post:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    /**
     * Código dos status existentes
     */
    const STATUS = [
        0 => 'Rascunho',
        1 => 'Publicado',
        2 => 'Excluído'
    ];

    /**
     * Lista de campos que podem ser submetidos em massa (form)
     *
     * @var array
     */
    protected $fillable = [
        'titulo', 'conteudo', 'status', 'capa'
    ];

    /**
     * Retorna o relacionamento de post com a tabela user
     * 
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function user()
    {
        return $this->belongsTo('App\Models\User');
    }

    /**
     * Traduz a sigla status para algo compreensivo
     * 
     * @return string
     */
    public function getStatusMutatorAttribute()
    {
        $status = self::STATUS;
        return $status[$this->status];
    }
}
  • There is, but it depends on the direction of the relation. You can post your User’s post methods ?

  • I edited the question and added the model user and post

2 answers

3


Forms are diverse:

Auth::user()->posts()->create($request->all());

or

$user = Auth::user()
if ($user)
{
    $user->posts()->create($request->all());
}

or

in class FormRequest in the method authorize()

class CadEditPost extends FormRequest
{
    public function authorize()
    {
         $this->merge(['user_id' => Auth::user()->id]);
         return true;
    }
}

or

Can create a Observer with the method saving:

class PostObserver {

    public function saving($model)
    {
        $model->user_id = Auth::user()->id;
    }

}

in class Post

class Post extends Model
{

    public static function boot()
    {
        parent::boot(); // TODO: Change the autogenerated stub
        parent::observe(new PostObserver());
    } 

Every time you save (save()) is past the id authenticated user.

Particularly, the first which is the most elegant form for this particular code, so everything will depend on your code and context. In certain systems where an audit of records is done who recorded a particular record the last would be the ideal.

1

In your Post you can also use the associate. It will insert the user ID in your Post. See on documentation.

public function adicionar(CadEditPost $request)
{        
    $post = new Post($request->all());

    $post->user()->associate(Auth::user());

    if($post->save()) {
        // Sucesso
    }
}

Browser other questions tagged

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