How to relate two records elegantly?

2

At some point in my application I'm creating a post and relating it 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!']);
}

There is a more "elegant" or appropriate way to generate this relationship instead of using:

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

Note: In the post user_id table is a foreign table that points to the users / p>

Is this form would 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];
    }
}
    
asked by anonymous 17.12.2016 / 20:14

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 the FormRequest class in the authorize()

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

or

You can create a Observer with the saving method:

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() ) the authenticated user's id is passed.

Particularly, the first one that is the most elegant way for that particular code, then, 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 form would be ideal.

    
18.12.2016 / 00:24
1

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

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

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

    if($post->save()) {
        // Sucesso
    }
}
    
18.12.2016 / 06:36