I wrote an API Code in laravel, and here my code, in this API I am using passport
class TransactionApi extends BaseController
{
public function __construct()
{
$this->middleware('client');
}
In the constructor, I call the client middleware
kernel.php
protected $routeMiddleware = [
...
'client' => CheckClientCredentials::class,
];
Here's my API service providers
protected function mapApiRoutes()
{
Route::prefix('api/v1')
->middleware('api')
->namespace($this->namespace)
->group(__DIR__ . '/../routes/api.php');
}
API routes
Route::group(['prefix' => 'transaction'], function () {
Route::get('all', 'TransactionApi#showAllWithPaginate');
Route::get('total_refund', 'TransactionApi#totalRefund');
Route::get('total_price', 'TransactionApi#totalPrice');
Route::get('/', 'TransactionApi#show');
});
User model
<?php
namespace Corals\User\Models;
use Corals\Foundation\Traits\Hookable;
use Corals\Foundation\Traits\HashTrait;
use Corals\Foundation\Transformers\PresentableTrait;
use Corals\Modules\CMS\Models\Content;
use Corals\Settings\Traits\CustomFieldsModelTrait;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Spatie\Activitylog\Traits\LogsActivity;
use Spatie\MediaLibrary\HasMedia\HasMediaTrait;
use Spatie\MediaLibrary\HasMedia\Interfaces\HasMediaConversions;
use Spatie\MediaLibrary\Media;
use Spatie\Permission\Traits\HasRoles;
use Yajra\Auditable\AuditableTrait;
use Corals\User\Traits\TwoFactorAuthenticatable;
use Corals\User\Contracts\TwoFactorAuthenticatableContract;
use Corals\User\Notifications\MailResetPasswordNotification;
use Corals\Modules\Subscriptions\Models\Subscription;
use Laravel\Passport\HasApiTokens;
class User extends Authenticatable implements HasMediaConversions, TwoFactorAuthenticatableContract
{
use
TwoFactorAuthenticatable,
HasApiTokens,
Notifiable,
HashTrait,
HasRoles,
Hookable,
PresentableTrait,
LogsActivity,
HasMediaTrait,
AuditableTrait,
CustomFieldsModelTrait;
protected $slack_url = null;
/**
* Model configuration.
* #var string
*/
public $config = 'user.models.user';
protected static $logAttributes = ['name', 'email'];
protected static $ignoreChangedAttributes = ['remember_token'];
protected $casts = [
'address' => 'json',
'notification_preferences' => 'array'
];
protected $appends = ['picture', 'picture_thumb'];
protected $dates = ['trial_ends_at'];
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $guarded = [
'id'
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token', 'two_factor_options'
];
public function __construct(array $attributes = [])
{
$config = config($this->config);
if (isset($config['presenter'])) {
$this->setPresenter(new $config['presenter']);
unset($config['presenter']);
}
foreach ($config as $key => $val) {
if (property_exists(get_called_class(), $key)) {
$this->$key = $val;
}
}
return parent::__construct($attributes);
}
Given that setup, testing locally is fine, it will return the requested json
But they same setup, on staging environment, returned
{
"message": "Call to undefined method Illuminate\\Auth\\GenericUser::withAccessToken()",
"exception": "Symfony\\Component\\Debug\\Exception\\FatalThrowableError",
"file": "/path/to/vendor/laravel/passport/src/Guards/TokenGuard.php",
"line": 148,
What are the posible cause why on staging
in this line
return $token ? $user->withAccessToken($token) : null;
undefined $user->withAccessToken function/method?
Related
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
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.
So i'm trying to make a like system for my imageshare.
For that i tried to use the "Laravel Follow" from overtrue but it's giving me problems.
Everytime i try to use the functions that he says in his GitHub page it always gives me "Call to undefined method App\Models\Photo::needsToApproveFollowRequests()".
This is my User.php
<?php
namespace App\Models;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Contracts\Auth\CanResetPassword;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;
use Overtrue\LaravelFollow\Followable;
class User extends Authenticatable implements MustVerifyEmail
{
use HasApiTokens, HasFactory, Notifiable, Followable;
/**
* The attributes that are mass assignable.
*
* #var string[]
*/
protected $fillable = [
'firstName',
'lastName',
'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',
];
}
And this is the function in my controller where I'm trying to use it:
public function getSnatch($id) {
//Let's try to find the image from database first
$image = Photo::find($id);
if(!$image) {
abort(404);
}
$imageThumb = Photo::find($id)->paginate(1);
$user = User::find($image->user);
$currentUser = User::find(auth()->user()->id);
// $user = User::where('id', $userID)->first();
$lastId = Photo::where('id', '<', $image->id)->max('id');
$nextId = Photo::where('id', '>', $image->id)->min('id');
// $nextPageNumber = $image->id + 1;
$maxId = Photo::find($id)->max('id');
$minId = Photo::find($id)->min('id');
// $imageCount = count(DB::table('photos')->get());
// ddd($nextId);
$likeImage = $currentUser->toggleFollow($image);
$totalLikes = $image->followers();
if ($lastId < $minId) {
$lastId = $maxId;
}
if ($nextId === NULL) {
$nextId = $minId;
}
//If found, we load the view and pass the image info asparameter, else we redirect to main page with errormessage
if($image) {
return View::make('tpl.permalink')
->with('image', $image)
->with('lastId', $lastId)
->with('nextId', $nextId)
->with('user', $user)
->with('imageThumb', $imageThumb)
->with('currentUser', $currentUser)
->with('likeImage', $likeImage)
->with('totalLikes', $totalLikes);
} else {
return Redirect::to('/')->with('error','Image not found');
}
}
Everything in the composer is well installed.
I also tried to delete the vendor folder, clear the cache of the composer and make composer install again, didn't work.
You have to override the method in your model that uses Followable trait.
public function needsToApproveFollowRequests()
{
// Your custom logic here
return (bool) $this->private;
}
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 !!
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