If I created a blog post, how can I have my name associated with it? For example, on a page that lists all blog posts, I will see the user name of the post they created. Yes?
In my post controller:
public function __construct(Post $post, User $user)
{
$this->middleware('auth',['except'=>['index','show',]]);
$this->post = $post;
$this->user = $user;
}
public function show($id)
{
$user = $this->user->first(); // This seems to show the first user
$post = $this->post->where('id', $id)->first(); // Grabs the assigned post
}
In my show.blade.php:
{{ $user->name }}
How can I display the name of the user who created the post? I thought this $user = $this->user->first(); would work. Im new to Laravel and I am using Laravel 5.
Thanks!
EDIT
User Model:
class User extends Model implements AuthenticatableContract, CanResetPasswordContract, BillableContract {
use Authenticatable, CanResetPassword;
use Billable;
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'users';
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = ['name', 'email', 'password', 'company_url', 'tagline','company_name', 'company_description'];
/**
* The attributes excluded from the model's JSON form.
*
* #var array
*/
protected $hidden = ['password', 'remember_token'];
/**
* #var array
*
*/
protected $dates = ['trial_ends_at', 'subscription_ends_at'];
public function posts()
{
return $this->hasMany('App\Post')->latest()->where('content_removed', 0);
}
}
Post Model:
class Post extends Model {
/**
* Fillable fields for a new Job.
* #var array
*/
protected $fillable = [
'post_title',
'post_description',
'post_role',
'post_types',
'post_city',
'post_country',
'template',
'content_removed',
];
public function users()
{
return $this->hasMany('App\User')->orderBy('created_at', 'DESC');
}
public function creator()
{
return $this->belongsTo('App\User');
}
}
first
you need to add the following line to your post model
public function creator()
{
return $this->belongsTo('App\User','user_id', 'ID');
}
then in you show method
public function show($id)
{
$post = $this->post->with('creator')->findOrFail($id);
return view('show',compact('post'));
}
In you show.blade.php
{{ $post->creator->name }}
Related
The relationship is User who can have many Events they are associated to.
I want to be able to make an API call to get all the events associated by the user. I have changed my primary key from id to uuid. I have made the foreign key association to the Events table as well. The primary key in the events table is also a column called UUID.
I am getting error
Return value of App\Http\Controllers\UsersController::getAllEvents() must be an instance of App\Http\Resources\UserResource, instance of Illuminate\Database\Eloquent\Relations\HasMany returned
My routes table:
Route::apiResource('/users', 'UsersController');
Route::apiResource('/events', 'EventsController');
Route::get('/users/allevents/{user}', 'UsersController#getAllEvents');
So the URL im hitting is:
http://127.0.0.1:8000/api/users/allevents/0a0jqZ7qzuhemKnzB3wOPUc2Ugp2
0a0jqZ7qzuhemKnzB3wOPUc2Ugp2 is the UUID of a user. I want to get all the events associated to that user.
My User model:
class User extends Model
{
use Notifiable;
use SoftDeletes;
protected $dates = ['deleted_at'];
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'uuid', 'email', 'firstName', 'lastName', 'level', 'venmo'
];
public function getRouteKeyName()
{
return 'uuid';
}
public function events() {
return $this->hasMany(Event::class);
}
}
My Event Model:
class Event extends Model
{
use SoftDeletes;
protected $table = 'events';
protected $dates = ['deleted_at'];
// public function getRouteKeyName()
// {
// return 'uuid';
// }
protected $fillable = [
'id', 'availableSpots', 'uuid', 'chosenDate', 'date', 'epochTime', 'level', 'price', 'time', 'created_at', 'updated_at', 'user_uuid'
];
public $incrementing = false;
protected $primaryKey = 'uuid';
protected $keyType = 'string';
public function user(){
return $this->belongsTo(User::class, 'user_uuid', 'uuid');
}
}
My UsersController:
class UsersController extends Controller
{
public function show(User $user): UserResource
{
return new UserResource($user);
}
/**
* #param Request $request
* #param User $user
* #return UserResource
*/
public function update(Request $request, User $user): UserResource
{
$user->update($request->all());
return new UserResource($user);
}
/**
* #param User $user
* #return UserResource
* #throws \Exception
*/
public function destroy(User $user): UserResource
{
$user->delete();
return new UserResource($user);
}
public function getAllEvents(User $user): UserResource {
return $user->events();
}
}
You are using wrong type of the method return it doesn't return UserResource it return events array so by removing the wrong type it will work
public function getAllEvents(User $user) {
return $user->events;
}
public function getAllEvents(User $user)
{
return $user->events;
}
In Laravel 5.8, I have a custom attribute to recover the avatar via Gravatar. This is an attribute in the User model.
/**
* #return string
*/
public function getAvatarAttribute()
{
return sprintf('%s%s%s', 'https://secure.gravatar.com/avatar/', md5(strtolower(trim($this->email))), '?s=200');
}
I have a belongsTo/hasMany relationship in the Post/User model.
Post model:
/**
* #return BelongsTo
*/
public function user(): BelongsTo
{
return $this->belongsTo(User::class);
}
User model:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use Notifiable;
/**
* #var string
*/
protected $table = 'users';
/**
* #var array
*/
protected $fillable = [
'username',
'email',
'password',
'api_token',
];
/**
* #var array
*/
protected $hidden = [
'password',
'remember_token',
'api_token',
];
/**
* #var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
'admin' => 'boolean',
];
/**
* #return string
*/
public function getRouteKeyName()
{
return 'username';
}
/**
* #return HasMany
*/
public function posts(): HasMany
{
return $this->hasMany(Post::class);
}
/**
* #return string
*/
public function getAvatarAttribute()
{
return sprintf('%s%s%s', 'https://secure.gravatar.com/avatar/', md5(strtolower(trim($this->email))), '?s=200');
}
}
I pass the post by the URL of the route:
Route::get('post/{post}', 'BlogController#post');
I would like to retrieve the avatar attribute via post. Only, I recover a null. And I do not understand where it comes from.
public function post(Post $post)
{
dd($post->user); // user model without appends attributes
dd($post->user->avatar); // null
}
I found the problem, I used User from Illuminate (Illuminate\Foundation\Auth\User) instead my User model.
i'm trying make an accessor, for post permalink. If i understand correctly it will change my premalink when i create new entry, but it doesn't
<?php
class Story extends Model
{
use UuidTrait;
public $incrementing = false;
protected $table = 'stories';
protected $fillable = [
'title', 'text', 'tags', 'user_id', 'permalink',
];
public function user()
{
return $this->belongsTo('App\Model\User', 'user_id');
}
/**
* Set the permalink.
*
* #param string $value
* #return void
*/
public function sePermalinkAttribute($value)
{
if(empty($value)){
$value = $this->attributes['title'];
}
$this->attributes['permalink'] = str_slug($value);
}
}
But i get NULL when save my model. Why does accessor not working?
$user->stories()->create($data['data']);
I am creating a user profile page and I want to retrieve the data from my User model and UserProfile model. But I have a problem in getting the result. Here's what I did:
User model
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'password', 'username',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
/*
public function isAdmin() {
return $this->admin;
}
*/
public function profile() {
return $this->hasOne('App\UserProfile');
}
}
UserProfile model
class UserProfile extends Model
{
protected $table = 'user_profile';
protected $fillable = [
'phone',
'address'
];
public function user() {
return $this->belongsTo('App\User');
}
}
Then I access the relation in my ProfileController
public function getProfile($username) {
$user = User::with('user_profile')->where('username', $username)->get();
dd($user);
}
And I got this error:
Call to undefined relationship [user_profile] on model [App\User].
The user_profile is my table name
Use proper relationship name:
$user = User::with('profile')->where('username', $username)->first();
Also, in this case you should use the first() method to get an user object.
I'm trying to get the 'name' field of the 'users' table in my Articles (REST) controller.
These are my models:
// models/Article.php
class Article extends Eloquent {
protected $fillable = [];
protected $table = 'articles';
public function user(){
return $this->belongsTo('User','user_id');
}
public function upload(){
return $this->has_one('Upload');
}
}
// models/User.php
class User extends Eloquent implements UserInterface, RemindableInterface {
use UserTrait, RemindableTrait;
protected $fillable = array('email','password','name');
public function articles(){
return $this->hasMany('Article','user_id');
}
/**
* Get the unique identifier for the user.
*
* #return mixed
*/
public function getAuthIdentifier()
{
return $this->getKey();
}
public function getAuthPassword()
{
return $this->password;
}
public function getReminderEmail()
{
return $this->email;
}
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'users';
/**
* The attributes excluded from the model's JSON form.
*
* #var array
*/
protected $hidden = array('password', 'remember_token');
}
// controllers/ArticlesController.php
class ArticlesController extends \BaseController {
public function index() // GET (all)
{
$articles = Article::all();
foreach ($articles as $article) {
// ** ERROR ** Undefined property: Illuminate\Database\Eloquent\Relations\BelongsTo::$id
var_dump("title: ".$article->titulo." | user: ".$article->user()->id .' | email: '.$article->user()->email );
}
}
// other functions [....]
}
So..How can I get the fields from 'users' table properly?? I've been searching in the Laravel doc and this web and... I haven't' found the error :(
I've set up the database relationships on the migrations files and I've checked out the mysql databases relations diagram and everything is ok.
Have you checked the keys properly. belongsTo's second parameter should be the local key whereas hasMany's second parameter is the foreign key.