Attempt to read property "name" on null (View: C:\xampp\htdocs\Moja_OTT\resources\views\premium\profile.blade.php) - laravel

I want a simple program that shows the user profile after login. I used session and middleware. But it is saying that the name property is null. Please help me solve this error. I have used User model. The value of the properties are not retrieving from the database.
Blade code:
<h1>Profile</h1>
<h2>Welcome Mr/Ms {{$user->name}}</h2>
Logout
Model:
<?php
namespace App\Models;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use App\Models\PremiumModel;
class User extends Authenticatable implements MustVerifyEmail
{
use HasFactory, Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $table = 'users';
protected $primaryKey = 'user_id';
protected $timestamp = false;
protected $fillable = [
'name',
'email',
'password',
'type',
'email_verified_at',
'pro_pic',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
function admin()
{
return $this->hasOne('App\Models\admin', 'user_id', 'admin_id');
}
function premium()
{
return $this->hasMany(PremiumModel::class, 'user_id', 'user_id');
}
}
Controller code:
function profile()
{
$user = User::where('user_id',session()->get('logged'))->first();
return view('premium.profile')->with('user',$user);
}
Here, logged is the middleware.

You can try hasOne in the User model:
public function premium()
{
return $this->hasOne(PremiumModel::class, 'user_id', 'user_id');
}
Because hasMany returned an array, but hasOne returned just a single Object

Related

Laravel Relationship Null

I am having an issue following a tutorial on YouTube about relationships.
I have replicated this code from the tutorial and I keep getting errors.
I've tried changing the controller code from auth() to app etc.
Also, I've tried re-running migrations:fresh etc and nothing.
User Model
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Cashier\Billable;
class User extends Authenticatable
{
use Notifiable, Billable;
/**
* The attributes that are mass assignable.
*
* #var string[]
*/
protected $fillable = [
'name',
'email',
'password',
];
/**
* The attributes that should be hidden for serialization.
*
* #var array
*/
protected $hidden = [
'password',
'remember_token',
];
/**
* The attributes that should be cast.
*
* #var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
/**
* Get the Instance associated with the user.
*
* #return HasMany
*/
public function instance()
{
return $this->hasMany(Instance::class);
}
}
Instance Model
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Instance extends Model
{
/**
* The attributes that are mass assignable.
*
* #var string[]
*/
protected $fillable = [
'name'
];
public function user()
{
return $this->belongsTo(User::class);
}
}
Controller
<?php
namespace App\Http\Controllers;
class SyncController extends Controller
{
public function successful()
{
return auth()->user()->instance()->create(['name' => 'test']);
}
}
Error
Call to a member function instance() on null {"exception":"[object] (Error(code: 0): Call to a member function instance() on null at /home/#/cc.#.io/app/Http/Controllers/SyncController.php:14)
[stacktrace]
Edit:
Route::middleware(['auth'])->group(function() {
Route::get('/dashboard', function () {
return view('dashboard');
})->name('dashboard');
Route::get('/subscribe', SyncController::class);
});
Check if your route is guarded by auth middleware. If not you can add that in order to fix. You might use Route group like following -
Route::group(['middleware' => ['auth']], function () {
Route::resource('your_url', 'YourController');
// Or whatever route you want to add...
});
This is because the auth()->user is getting null and it will be necessary to check if the value was actually received after the call was made.

compatible with Illuminate\Foundation\Auth\User::sendEmailVerificationNotification()

I need to change default resetpassword message so i make my own ResetPassword notification and when i do that I got this Error Declaration of App\User::sendEmailVerificationNotification($token) should be compatible with Illuminate\Foundation\Auth\User::sendEmailVerificationNotification()
code in User model:
<?php
namespace App;
use App\admin\Course;
use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable implements MustVerifyEmail
{
use Notifiable; // حتى اقدر ارسل اله اشعار
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'password','type','mobile',
];
/**
* 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 courses()
{
return $this->belongsToMany(Course::class, 'course_user', 'user_id', 'course_id');
}
public function routeNotificationForNexmo($notification)
{
return $this->mobile;
}
public function sendPasswordResetNotification($token)
{
$this->notify(new \App\Notifications\ResetPassword($token));
}
public function sendEmailVerificationNotification($token)
{
$this->notify(new \App\Notifications\VerifyEmail($token));
}
}
Why !!

Laravel 5.6 -> POST http://127.0.0.1:8000/posts 500 (Internal Server Error)

When I Am trying to access API and add the protected $appends = ['avatar'] it gives me the error while in case I remove the $appends the error go.
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'username', 'email', 'password',
];
protected $appends = ['avatar'];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
public function posts()
{
return $this->hasMany(Post::class);
}
public function getAvatar(){
return 'https://gravatar.com/avatar/'.md5($this->email).'/?d=mm&s=45';
}
public function getAvatarAtribute(){
return $this->getAvatar();
}
}
When I go to the network trace I see this tip -> message: "Method Illuminate\Database\Query\Builder::getAvatarAttribute does not exist."
Just checked your code you have to declare as
public function getAvatarAttribute(){
return $this->getAvatar();
}
Attribute instead of atribute

Returning null Value for User from Model

I'm getting a null value for the user at http://localhost:8000/messages. I am trying to get the user table values within the Message model. It also gives a null value in the console.
Route
Route::get('/messages', function () {
return App\Message::with('user')-> get();
})-> middleware('auth');
Model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Message extends Model
{
protected $fillable = ['message'];
public function user()
{
return $this->belongsTo(User::class);
}
}
User Model code:
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
public function messages()
{
return $this-> hasMany(Message::class);
}
}
Snapshot
messages table must have user_id with proper user ID to make belongsTo relationship work.
https://laravel.com/docs/5.5/eloquent-relationships#one-to-many-inverse

How do I read database data from default User class in Laravel?

When I use the following code in my routes/web.php file, I keep getting the error of 'Trying to get property of non-object' each time I visit the /user/{id}/post url.
routes/web.php
use App\Post;
use App\User;
Route::get('/user/{id}/post', function($id) {
return User::find($id)->name;
});
App/User.php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
public function posts() {
return $this->hasOne('Post');
}
}
App/Post.php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Post extends Model
{
// protected $table = 'posts';
use SoftDeletes;
protected $dates = ['deleted_at'];
protected $fillable = [''];
}
How do I view data stored in the table users? I put some dummy data in there to try and retrieve it.
If user hasOne relation with Post,it is better to make relation post() rather than posts() and post belongsTo user.
User Model:
public function post() {
return $this->hasOne('App\Post');
}
Post Model:
public function user()
{
return $this->belongsTo('App\User');
}
then, this gives all user's post along with user name.
$users=User::with('post')->get();
foreach($users as $user)
{
print_r($user->name);
print_r($user->post);
}

Resources