This is my PlayerController, Player & Session Model and Resource.
I want to use the input (sessionId from SessionsTable) to fetch user from the room with the same id (userSession) and return an array in this format: [{userId:1, userName: stacki, userVote:8},{...},...]
I already asked [here][1] to achieve this and now im stuck with this error.
What do I have to change in order to solve this issue? Simply adding ->first() does not solve my issue, I need more than one record.
namespace App\Http\Controllers;
use App\Player;
use Illuminate\Http\Request;
use App\Http\Resources\Players as PlayerResource;
class PlayerController extends Controller
{
public function index(Request $request)
{
$room = $request->input('sessionId');
$currentPlayers = Player::where('userSession', $room)->get();
return PlayerResource::collection($currentPlayers);
}
public function create()
{ }
public function update()
{ }
}
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Player extends Model
{
protected $fillable = [];
public $sortable = [
'userId',
'userName',
'userVote'
];
public function sessions()
{
return $this->hasMany('App\Session');
}
public function players(){
return $this->belongsToMany('App\Session');
}
}
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Session extends Model
{
protected $fillable = [];
public function user(){
return $this->belongsToMany('App\Player');
}
public function creator()
{
return $this->hasOne('App\Player', 'userId');
}
}
class Players extends ResourceCollection
{
/**
* Transform the resource collection into an array.
*
* #param \Illuminate\Http\Request $request
* #return array
*/
public function toArray($request)
{
return [
'userId' => $this->sessionId,
'userName' => $this->userName,
'userVote' => $this->userVote
];
}
}
`
[1]: https://stackoverflow.com/questions/58062014/display-db-entries-in-json-array-in-controller-laravel-php
Your Player class might extends the Illuminate\Http\Resources\Json\JsonResource instead of ResourceCollection.
This should solve your problem.
use Illuminate\Http\Resources\Json\JsonResource;
class Players extends JsonResource
{
/**
* Transform the resource collection into an array.
*
* #param \Illuminate\Http\Request $request
* #return array
*/
public function toArray($request)
{
return [
'userId' => $this->sessionId,
'userName' => $this->userName,
'userVote' => $this->userVote
];
}
}
Hope it helps.
Related
I have an user model and a student model which I have created relationship for, but when I try to
$student->user->fullname
I get this error
"trying to get property fullname of non-object"
here is my user model code:
<?php
namespace App;
use App\Assignment;
use App\Model\Quiz;
use App\Model\Course;
use App\Topic;
use App\Model\Guardian;
use App\Model\Student;
use App\Model\Teacher;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Spatie\Permission\Traits\HasRoles;
class User extends Authenticatable implements MustVerifyEmail
{
use Notifiable, HasRoles, SoftDeletes;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'fullname',
'email',
'avatar',
'password',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
public function setPasswordAttribute($password)
{
$this->attributes['password'] = bcrypt($password);
}
public function guardian()
{
return $this->belongsTo(Guardian::class);
}
public function teacher()
{
return $this->belongsTo(Teacher::class);
}
public function student()
{
return $this->belongsTo(Student::class);
}
public function assignments()
{
return $this->hasMany(Assignment::class);
}
public function quizzes()
{
return $this->hasMany(Quiz::class);
}
public function courses()
{
return $this->hasMany(Course::class);
}
public function topics()
{
return $this->hasMany(Topic::class);
}
public function levels()
{
return $this->hasMany(Level::class);
}
}
and here is my student model code
<?php
namespace App\Model;
use App\User;
use App\Model\Course;
use App\Assignment;
use App\Level;
use App\Model\DoneQuiz;
use App\Model\Teacher;
use App\Model\Guardian;
use Illuminate\Database\Eloquent\Model;
class Student extends Model
{
protected $fillable = ['user_id', 'level_id', 'guardian_id'];
public function user()
{
return $this->belongsTo(User::class);
}
public function courses()
{
return $this->hasMany(Course::class);
}
public function assignments()
{
return $this->hasMany(Assignment::class);
}
public function level()
{
return $this->hasOne(Level::class);
}
public function teachers()
{
return $this->hasMany(Teacher::class);
}
public function guardian()
{
return $this->hasOne(Guardian::class);
}
public function donequizzes()
{
return $this->hasMany(DoneQuiz::class);
}
}
and even when I try to use this relationship to get data like
'student_id' => auth()->user()->student()->id
I get this error
"BadMethodCallException Call to undefined method
Illuminate\Database\Eloquent\Relations\BelongsTo::id()"
when you use student() it returns a query builder
Either change it to simple student
'student_id' => auth()->user()->student->id
OR
'student_id' => auth()->user()->student()->first()->id
I am trying to implement policies in my project. All tries have proven unsuccessful despite following documentation to the letter. And also read numerous posts on SO about it and other media. I did as described in docs, but nonetheless it doesn't work. What gives?
In AuthServiceProvider:
<?php
namespace App\Providers;
use App\User;
use App\Job;
use App\Policies\JobPolicy;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
use Illuminate\Support\Facades\Gate;
class AuthServiceProvider extends ServiceProvider
{
/**
* The policy mappings for the application.
*
* #var array
*/
protected $policies = [
'App\Job' => 'App\Policies\JobPolicy',
//Job::class => JobPolicy::class,
];
/**
* Register any authentication / authorization services.
*
* #return void
*/
public function boot()
{
$this->registerPolicies();
//
}
}
In policy:
<?php
namespace App\Policies;
use App\Job;
use App\User;
use Illuminate\Auth\Access\HandlesAuthorization;
class JobPolicy
{
use HandlesAuthorization;
/**
* Determine whether the user can view any jobs.
*
* #param \App\User $user
* #return mixed
*/
public function viewAny(User $user,Job $job)
{
//return (($user->isAdmin() || $user->isModerator() || $user->isUser()) && $user->status==1);
//return ($user->isMod());
return true;
}
In controller:
public function index()
{
$this->authorize('viewAny', User::class, Job::class);
return view("jobs.index");
}
My User model:
<?php
namespace App;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use App\Role;
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'password',"role_id"
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
public function role(){
return $this->belongsTo("App\Role", "role_id");
}
public function isMod()
{
$user = User::find(auth()->user()->id);
$role = $user->role()->first()->name;
if($role==="job board moderator"){
return true;
}
else{
return false;
}
}
}
And Job model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use App\User;
class Job extends Model
{
protected $fillable = [
"title", "description", "email"
];
public function user(){
return $this->belongsTo("App\User","user_id");
}
}
In policy:
public function viewAny(User $user)
{
return true;
}
In controller:
public function index()
{
$this->authorize('viewAny', Job::class);
return view("jobs.index");
}
The way to call a model policy method changes depending on the number of parameters it has.
No object
/* In policy*/
public function viewAny(User $user)
/* In controller */
$this->authorize('viewAny', Job::class)`
1 object
/* In policy*/
public function view(User $user, Job $job)
/* In controller */
$this->authorize('view', $job)
More than 1 object
/* In policy*/
public function view(User $user, Job $job, AnotherModel $model)
/* In controller */
$this->authorize('view', [$job, $model])
Source: https://laravel.com/docs/5.8/authorization#creating-policies
I made a socialite login using Google and Facebook, but in the SocialiteController section there is an error like the question above.
this is my SocialiteController
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Laravel\Socialite\Facades\Socialite;
use Illuminate\Support\Facades\Auth;
use Spatie\Permission\Models\Role;
use App\SocialAccount;
use App\User;
class SocialiteController extends Controller
{
public function redirectToProvider($provider)
{
return Socialite::driver($provider)->redirect();
}
public function handleProviderCallback($provider)
{
$user = Socialite::driver($provider)->user();
$authUser = $this->findOrCreateUser($user, $provider);
Auth::login($authUser, true);
return redirect('/personal');
}
public function findOrCreateUser($socialUser, $provider)
{
$socialAccount = SocialAccount::where('provider_id', $socialUser->getId())
->where('provider_name', $provider)
->first();
if($socialAccount) {
return $socialAccount->user;
} else {
$user = User::where('email', $socialUser->getEmail())->first();
if(!$user) {
$user = User::create([
'username' => $socialUser->getName(),
'email' => $socialUser->getEmail()
]);
$user->assignRole('Registered');
}
$user->socialAccounts()->create([
'provider_id' => $socialUser->getId(),
'provider_name' => $provider
]);
return $user;
}
}
}
this is my User model
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Spatie\Permission\Traits\HasRoles;
use App\Profile;
use App\Article;
use App\Video;
use App\Images;
use App\News;
class User extends Authenticatable Implements MustVerifyEmail
{
use Notifiable, HasRoles;
protected $table = "users";
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'username', 'email', 'password'
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
public function profile(){
return $this->hasOne(Profile::class);
}
public function article()
{
return $this->hasMany(Article::class);
}
public function socialAccounts()
{
return $this->hasOne(SocialAccount::class);
}
public function video(){
return $this->hasMany(Video::class);
}
public function news(){
return $this->hasMany(News::class);
}
}
the complete error message like this :
Argument 1 passed to Illuminate\Auth\SessionGuard::login() must implement interface Illuminate\Contracts\Auth\Authenticatable, null given, called in /home/asyj6686/public_html/sublaravel/vendor/laravel/framework/src/Illuminate/Auth/AuthManager.php on line 297
Argument 1 passed to Illuminate\Auth\SessionGuard::login() must implement interface Illuminate\Contracts\Auth\Authenticatable, null given
This error is pretty straight-forward. It means that you have passed a null value to the login.
Auth::login($authUser, true);
I don't see anything wrong with the provided code. Therefore, I'm going to guess that you may have simply forgotten to add the inverse relationship with User in the SocialAccount model. This would cause $socialAccount->user to return null and generate the error you are receiving.
App\SocialAccount.php
class SocialAccount extends Model
{
// ...
public function user()
{
return $this->belongsTo(User::class);
}
}
On a side note, shouldn't a User be able to ->hasMany() SocialAccounts?
I'm making a function that each time I add a comment to an RMA Ticket it sends an email to the user but I'm getting Trying to get property of non-object when I submit the comment
Below I pasted the code from the CommentController and the Email function
if you want more information just ask and i will post what i could
I'm getting the error on this code - $mailer->sendRmaTicketComments($comment->ticket->user, Auth::user(), $comment->ticket, $comment);
CommentController Code
<?php
namespace App\Http\Controllers\Rma;
use Auth;
use App\User;
use App\Rma\RmaTicket;
use App\Rma\RmaComments;
use App\Mailers\AppMailer;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
class RmaCommentController extends Controller
{
public function postComment(Request $request, AppMailer $mailer)
{
$this->validate($request, [
'comment' => 'required',
'user_id' => 'required',
]);
$comment = RmaComments::create([
'rma_ticket_id' => $request->input('ticket_id'),
'user_id' => $request->input('user_id'),
'comment' => $request->input('comment'),
]);
$mailer->sendRmaTicketComments($comment->ticket->user, Auth::user(), $comment->ticket, $comment);
return redirect()->back()->with('successPanel', 'Thank you for your message please allow up to 48 hours for a response.');
}
}
Mail Function Code
<?php
namespace App\Mailers;
use App\Rma\RmaTicket;
use App\Rma\RmaStatus;
use App\SupportTickets\SupportTicket;
use App\SupportTickets\SupportTicketStatus;
use App\User;
use Illuminate\Contracts\Mail\Mailer;
use Illuminate\Support\Facades\Mail;
class AppMailer
{
protected $mailer;
/**
* Get the email address
*
* #var [type]
*/
protected $to;
/**
* Set the subject for the email
*
* #var [type]
*/
protected $subject;
/**
* Set the template for the email
*
* #var [type]
*/
protected $view;
/**
* Set the data for the email
*
* #var array
*/
protected $data = [];
public function __construct(Mailer $mailer)
{
$this->mailer = $mailer;
}
/**
* Send RMA Comments/Replies to RMA Owner
*
* #param User $ticketOwner
* #param User $user
* #param rmaTicket $rmaTicket
* #param Comment $comment
*
* #return method delivered()
*/
public function sendRmaTicketComments($ticketOwner, $user, RmaTicket $rmaTicket, $comment)
{
$this->to = $ticketOwner->email;
$this->subject = "RE[RMA Ticket # $rmaTicket->rma_ticket_id]";
$this->view = 'emails.rma.rma_comments';
$this->data = compact('ticketOwner', 'user', 'rmaTicket', 'comment');
return $this->deliver();
}
RmaComments Model
<?php
namespace App\Rma;
use Illuminate\Database\Eloquent\Model;
class RmaComments extends Model
{
protected $table = 'rma_comments';
protected $fillable = [
'rma_ticket_id', 'user_id', 'comment'
];
public function ticket()
{
return $this->belongsTo(RmaTicket::class);
}
public function user()
{
return $this->belongsTo(User::class);
}
}
RMA Model
<?php
namespace App\Rma;
use Illuminate\Database\Eloquent\Model;
class RmaTicket extends Model
{
protected $table = 'rma_tickets';
protected $fillable = [
'user_id', 'rma_ticket_id', 'first_name', 'last_name',
'email', 'fax', 'company', 'marketplace_id', 'returnTypeId',
'product_name', 'quantity', 'order_number', 'address_one',
'address_two', 'city', 'state', 'zip_code', 'sku', 'model_number', 'comment',
'status_id', 'rma_number', 'refund_number', 'return_tracking_number',
'replacement_number', 'return_label'
];
public function returnType()
{
return $this->belongsTo(RmaReturnType::class);
}
public function marketplace()
{
return $this->belongsTo(RmaMarketplace::class);
}
public function status()
{
return $this->belongsTo(RmaStatus::class);
}
public function comments()
{
return $this->hasMany(RmaComments::class);
}
public function user()
{
return $this->belongsTo(User::class);
}
}
Looking at your code and since you have null if you dd($comment->ticket) i believe it's the naming of your foreign keys.
your belongsTo:
public function ticket()
{
return $this->belongsTo(RmaTicket::class);
}
expects an ticket_id but you named it rma_ticket_id.
You could specify a different foreign key name in the second argument in the belongTo relationship
public function ticket()
{
return $this->belongsTo(RmaTicket::class, 'rma_ticket_id');
}
As per the docs:
. Eloquent determines the default foreign key name by examining the name of the relationship method and suffixing the method name with _id. However, if the foreign key on the Phone model is not user_id, you may pass a custom key name as the second argument to the belongsTo method:
ERROR: ErrorException in 814a6fb85b2cceb262c3a8191c08e42742940fc7.php line 223: Trying to get property of non-object (View: /var/www/html/m/TS/resources/views/d/show-details.blade.php)
Actually I am trying to get the username who has stored the result in the database i.e. TN has got user_id as a foreign key in the table so I need to get the username from that user_id using models but I am getting this problemTrying to get property of non-objectwhen I try to get theusername` associated with the id. I dont know where I am doing it wrong.
THE ERROR I AM GETTING IS HERE value="{{$tn->users->username}}" WHICH SHOWS IN THE CACHED FILE.
I have given my code below too to look.
Thank you in advance
Controller
public function details($id) {
$d= $this->detail->showDetails($id);
$tn= TN::find($id);
// calling functions from Model
$n = $d->tN;
$o = $d->tO;
return view('details.show-details', compact('d','o', 'n', 'tn'));
}
View
foreach($n as $n)
<input style="font-size:10px;font-weight: bold; color:black; background:#59d864;" value="{{$tn->users->username}}" readonly>
Models
User Model
<?php
namespace App;
use Illuminate\Foundation\Auth\User as Authenticatable;
use App\TN;
use App\TO;
use App\UserType;
class User extends Authenticatable
{
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'username', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
public function tN() {
return $this->hasMany(TN::class);
}
public function tO() {
return $this->hasMany(TO::class);
}
public function userType() {
return $this->belongsTo(UserType::class);
}
}
TO Model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use App\D;
use App\TT;
use App\User;
class TO extends Model
{
protected $fillable = ['o', 'date'];
public function d() {
return $this->belongsTo(D::class);
}
public function tOType() {
return $this->belongsTo(TOType::class);
}
public function users() {
return $this->belongsTo(User::class);
}
}
TN Model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use App\Debtor;
use App\TracingType;
use App\User;
class TN extends Model
{
protected $fillable = ['r', 'date'];
public function d() {
return $this->belongsTo(D::class);
}
public function tType() {
return $this->belongsTo(TType::class);
}
public function users() {
return $this->belongsTo(User::class);
}
}
Hello I have sorted this problem but forgot to post it in here the problem was here
public function users() {
return $this->belongsTo(User::class);
}
This should be public function user() rather than users. Because it belongsTo to User class, it should be singular not plural and for hasMany we use plurals. Thank you for your help though ... :)