How can i solve this error using "Laravel Follow" - laravel

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;
}

Related

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

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

403 user does not have any necessary access rights in laravel usercontroller laratrust

I am trying to get all user in my table but I get an error 403 user does not have the necessary rights. I am using laratrust and vuejs. I have already logged in as a superadministrator. This is my controller class
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\user;
use Illuminate\Support\Facades\Hash;
class UserController extends Controller
{
public function __construct()
{
$this->middleware('role:user|superadministrator');
}
public function index()
{
return view('user.index');
}
public function getusers(){
$theUser = Auth::user();
if ($theUser->hasRole('superadministrator')) {
return $users;
}
}
}
My api route
Route::get('/allusers','UserController#getusers');
I have tried to go through the documentation but no success.Kindly help me solve this issue
User Model
<?php
namespace App;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laratrust\Traits\LaratrustUserTrait;
class User extends Authenticatable
{
use LaratrustUserTrait;
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',
];
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
}
What about if you try this:
public function getusers(Request $request){
$theUser = $request->user('api');
if ($theUser->hasRole('superadministrator')) {
return $users;
}
}

Laravel Job class has incomplete passed model

I am trying to pass a model to job class and when the model is sent to job class, it's incomplete there. What I mean is that it shows only two attributes there instead of 10. $queue_match is complete model (all attributes included, everything is fine) but when it is sent to Job class, then I only see two attributes.
PS: I have included my model at the top of Job class,
$z = dispatch(new updateMatchStatus($queue_match))->onConnection('database')->delay(now()->addMinutes('1'));
namespace App\Jobs;
use App\Http\Controllers\AdminController;
use App\Models\Match;
use Carbon\Carbon;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
class updateMatchStatus implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
protected $queue_match;
/**
* Create a new job instance.
*
* #return void
*/
public function __construct(Match $queue_match)
{
//
$this->queue_match = $queue_match;
// dd($queue_match);
}
/**
* Execute the job.
*
* #return void
*/
public function handle(Match $queue_match)
{
$now = Carbon::now('PKT');
$now = Carbon::parse($now, 'PKT')->startOfMinute();
// registration close hack, will set Match status to F 30 mins before due time.
$now = $now->addMinutes(30);
$due_time = Carbon::parse($queue_match->due_time, 'PKT');
if ($now->greaterThan($due_time)) {
$queue_match->status = 'F';
// dd($queue_match);
$queue_match->save();
}
}
}
just two attributes in Screenshot
As requested, Here is Match Class
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Match extends Model
{
//
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'platform', 'category', 'map', 'fee', 'is_elite', 'due_time', 'status'
];
public function getPlatformAttribute($value) {
if ($value == 'M') {
return $value ."obile";
}
else {
return $value ."mulator";
}
}
// default attributes
protected $attributes= [
'status' => 'A',
'is_elite' => false
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
// hidden fields for return response
protected $hidden = [
'created_at', 'updated_at',
];
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $casts = [
];
public function registrations() {
return $this->hasMany('App\Models\Registration', 'match_id', 'id');
}
public function results() {
return $this->hasMany('App\Models\Result', 'match_id', 'id');
}
}
AND, this is how I get the $queue_match which is passed to job.
$queue_match = Match::create([
'category' => $request['category'],
'platform' => $request['platform'],
'map' => $request['map'],
'fee' => $request['fee'],
'due_time' => $request['due_time'],
]);

undefined $user->withAccessToken function/method

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?

BadMethodCallException in Builder.php line 2440: Call to undefined method Illuminate\Database\Query\Builder::getIdArray()

I'm creating role method in laravel, but when I start the page I have this error. If anyone has any idea you can share it. Thank you.
This is my User model
<?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 roles(){
return $this->belongsTo(App\Role);
}
public function isEmployee(){
return ($this->roles()->count()) ? true : false;
}
public function hasRole($role){
return (in_array($this->roles->pluck("names"), $role));
}
private function getIdInArray($array, $term){
foreach ($array as $key => $value){
if($value == $term){
return $key;
}
}
throw new UnexpectedValueException;
}
public function makeEmployee($title){
$assigned_roles = array();
$roles = Role::all()->pluck("name", "id");
switch($title){
case 'super_admin':
$assigned_roles[] = $this->getIdArray($roles, 'create');
$assigned_roles[] = $this->getIdArray($roles, 'update');
case 'admin':
$assigned_roles[] = $this->getIdArray($roles, 'delete');
$assigned_roles[] = $this->getIdArray($roles, 'ban');
case 'moderator':
$assigned_roles[] = $this->getIdArray($roles, 'kickass');
$assigned_roles[] = $this->getIdArray($roles, 'lemons');
break;
default:
throw new \Exception("The employee status entered does not exist");
}
$this->roles()->sync($assigned_roles);
}
}

Resources