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 ?
– gmsantos
I edited the question and added the model user and post
– Fábio Jânio