Laravel Befriended revoke method not working - php

I'm trying to remove a follower but the revokeFollower() method returns nothing and not working. Using the Laravel Befriended https://github.com/renoki-co/befriended package.
public function unfollowFollowers(Request $request){
$loginUser = Auth::user();
return $loginUser->revokeFollower($request['id']);
}
User.php
use Rennokki\Befriended\Traits\Follow;
use Rennokki\Befriended\Contracts\Following;
use Rennokki\Befriended\Scopes\FollowFilterable;
class User extends Authenticatable implements Following
{
use Notifiable,Follow,FollowFilterable;
}

On the README there is mentioned:
Note: Following, unfollowing or checking if following models that do not correctly implement CanBeFollowed and Followable will always return false.

Related

Call a Model method using Laravel Relationship

I'm currently trying to use Laravel Relationships to access my achievements Model using User model, I use this relationship code:
public function achievements()
{
return $this->hasMany('App\Models\User\Achievement');
}
I can easily make some eloquent queries, however I can't access any method that I created there, I can't access this method:
class Achievement extends Model
{
public function achievementsAvailableToClaim(): int
{
// Not an eloquent query
}
}
Using the following code:
Auth::user()->achievements()->achievementsAvailableToClaim();
I believe that I am using this Laravel function in the wrong way, because of that I tried something else without using relationship:
public function achievements()
{
return new \App\Models\User\Achievement;
}
But that would have a performance problem, because would I be creating a new class instance every time I use the achievements function inside user model?
What would be the right way of what I'm trying to do?
it's not working because your eloquent relationship is a hasMany so it return a collection. you can not call the related model function from a collection.
you can var dump it on tinker to understand more what i mean.
You can use laravel scopes.Like local scopes allow you to define common sets of constraints that you may easily re-use throughout your application.
In your case you use this like, Define scope in model:
public function scopeAchievementsAvailableToClaim()
{
return $query->where('achivement_avilable', true);
}
And you can use this like :
Auth::user()->achievements()->achievementsAvailableToClaim();

Why does only some laravel routes return model attributes?

i´m studying laravel but having some doubts..
Controller
namespace App\Http\Controllers;
use App\ItemNfe;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
class ItensNfeController extends Controller
{
public function edit($id,ItemNfe $itemNfe)
{
//i don´t want to have to make this select below
//$itemNfe = DB::table('itens_nfe')->where('id_itemnfe',$id)->get();
// dd($itemNfe); this dd() returns model attributes on few of my controllers only
return view...
}...
Model: (note i´m not using laravel convention but it´s informed)
namespace App;
use Illuminate\Database\Eloquent\Model;
class ItemNfe extends Model
{
protected $table = 'itens_nfe';
protected $primaryKey = 'id_itemnfe';
protected $fillable = [
'id_itemnfe','fk_venda', 'fk_produto'...
];
public function nfe()
{
return $this->belongsTo('App\Nfe'); //this is one diference among others models, but apparently doesn´t affects when i tested without this code.
}
}
The route i´m using is the same for everyone.. "resource routes"
At the first 2, i have the attributes returning, but not at the last one...
Route::resource('/usuarios', 'UsuariosController');
Route::resource('/nfes', 'NfesController');
Route::resource('/itensnfe', 'ItensNfeController');
The Url used is:
https://localhost/erpoverweb/public/itensnfe/1/edit
If needing more code please tell me... thanks!
If you don't want to manually search the database for the entry, you can use Laravel Container do perform a Dependency Injection. https://laravel.com/docs/7.x/container#introduction
public function edit(ItemNfe $itemNfe)
{
// Returns the model, and you didn't need to manually searched.
// Laravel automaticly injects this for you.
dd($itemNfe);
}
Sounds like you are looking for Route Model Binding (implicit at that). This requires that the route parameter name and the name of the parameter of the method signature for that route match.
public function edit(ItemNfe $itensnfe)
The resource route with resource name 'itensnfe' should make the parameter 'itensnfe'.
If you don't make these match you will just end up with Dependency Injection which would inject a new model instance.
Laravel 7.x Docs - Routing - Route Model Binding - Implicit Binding

How to validate credentials in laravel 5 for logging in features?

I am new to Laravel and I am using tutorial for web app. Tutorial uses Laravel 4 whereas I am using Laravel 5. I solved register issue but when I set down to test for login following errors shown up:
ErrorException in EloquentUserProvider.php line 111: Argument 1 passed to Illuminate\Auth\EloquentUserProvider::validateCredentials() must be an instance of Illuminate\Contracts\Auth\Authenticatable, instance of App\user given, called in C:\Users\Pujan\Desktop\projectlaravel\vendor\laravel\framework\src\Illuminate\Auth\Guard.php on line 390 and defined.
I'm not able to figure out the issue here. What actually means credentials. I know Laravel 5 has inbuilt login features but couldn't use it so I tried out different ways but this problem out of my focus.
My usercontroller is:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use View;
use App\user;
use Input;
use App\Http\Requests\YourFormRequest;
use Auth;
//use Illuminate\Support\Facades\Auth;
class UserController extends Controller
{
public $restful = true;
public function index()
{
return View::make('users.new')->with('title', 'Make it snappy Q&A - Register');
}
public function create(YourFormRequest $request)
{
User::create($request->all());
return redirect('/')->with('message','Thanks for registering!');
}
public function getlogin()
{
// return \Auth::user();
return View::make('users.login')->with('title','Make it snappy Q&A - Login ');
}
public function createlogin()
{
$user = array(
'username'=>Input::get('username'),
'password'=>Input::get('password')
);
if (Auth::attempt($user))
{
return redirect('/')->with('message','You are logged in:');
}else{
return redirect('login')
->with('message','Your username or password are incorrect pls chk it out')
->with_input();
}
}
I have my routes:
Route::get('/','Questions#index');
Route::get('register','UserController#index');
Route::get('login','UserController#getlogin');
Route::post('register','UserController#create');
Route::post('login','UserController#createlogin');
My login layout is working properly but as I try to login above errors show up. I think this error belongs to inbuilt Laravel 5 features but I am not able to match the setting inbuilt and my created login functionality.
The error you're seeing isn't related to your login code. Your User entity should implement the Illuminate\Contracts\Auth\Authenticatable interface. An interface is a contract, it lists methods/functions that a class must have. The class definition should look like this:
class User extends Model implements Authenticatable
{
On a quick glance of your code, there are other things you can do to clean it up:
public function createlogin()
{
if (Auth::attempt(Input::only('username', 'password'))) {
return redirect('/')->with('message','You are logged in:');
}
return redirect('login')
->with('message','Your username or password are incorrect pls chk it out')
->with_input();
}
And on a final note, I'd stop using the tutorial you're following. Laravel's latest documentation has a quick start guide that covers authentication, there are two versions, beginnner and intermediate.
What #Logan has suggested is true, and you should follow that.
I'll just go with cleaning of your code a bit.
Whenever you are dealing with validations, you should treat it as a separate stuff and for that you need to create the FormRequest object.
Refer this document on how to create the form request.
Then update the authorize and rules method with the following:
/**
* Authorize the request.
*
* #return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
return [
'username' => 'required|exists:users|alpha_dash|min:4',
'password' => 'required'
];
}
Now in your createLogin method
/**
* Log in the user.
*
* #param \App\Http\Requests\YourFileRequest $request
* #return \Illuminate\Http\RedirectResponse
*/
public function createlogin(YourFileRequest $request)
{
$credentials = $request->only('username', 'password');
if (Auth::attempt($credentials)) {
return redirect('/')->with('message','You are logged in:');
}
return redirect('login')
->with('message', 'Invalid credentials')
->with_input();
}
Now you see how your code is simple and readable when you visit after 6 months from now ? It has to be like that. Validation logic in separate file and your Login logic in the controller. According to me, this helps a lot when you are testing via phpUnit, phpSpec or any other testing tool you are using.
Me and Logan have also replaced your if statement block. That is because, you should avoid the else block as far as possible when you are returning something from both if and else block.
Just a side note:
You should always try to follow 3 principles while programming / coding: SOLID, KISS, and DRY.
Kindly document your code whenever you are done with that part of the code. This is will again help future programmers and also for future reference to know what that piece of code is doing.
Hope this helps you out. Cheers.
Not sure whether you have solved this issue or not but I'm putting my experience here, maybe it could help someone else looking for a solution to this problem which happened exactly with me.
Your App/User model class should extends Illuminate\Foundation\Auth\User and not the Eloquent Model.
So change your User model to this:
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
Instead of
class User extends Model
It did resolve this same error for me. Hope this helps.

Unable to access related eloquent models when calling the user object through Auth::User() in Laravel 5

I'm just running through the process of upgrading my app to Laravel 5. I was using the Laravel 4 user authentication library, along with my own 'Profile' model, for storing user profile information, defined like this:
User model:
class User extends Eloquent implements AuthenticatableContract, CanResetPasswordContract {
//...
public function Profile()
{
return $this->hasOne('Profile');
}
//..
}
Profile model:
class Profile extends Eloquent {
//...
public function User()
{
return $this->belongsTo('User');
}
//...
}
Previously (when the app was Laravel 4), I would be able to access the profile for the logged in user by loading the user object through the Auth facade:
$user = Auth::user();
echo $user->profile->picture;
However, since upgrading to Laravel 5 this has been throwing a Trying to get property of non-object error.
I am able to load the profile, via the user, if I load the user object directly through the user model, like this:
$user = User::findOrFail(Auth::user()->id)->first();
echo $user->profile->picture;
...but this seems like a long-winded way of doing it.
Is there a better way, or is there something I'm missing? Any help appreciated.
If it's what I think it is, then you might need to update config/auth.php's model option to be your user model's class name.
This property is the model that laravel's auth driver will use. By default, it is App\User.

Laravel 4 BadMethodCallException upon calling a method of a model

I created a User class in Laravel application as follows:
<?php
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableInterface;
class User extends Eloquent implements UserInterface, RemindableInterface {
...
public function hasAnyRoles()
{
return true;
}
The function there is simplified to always return true for the purposes of this example. I pretty much followed this tutorial here to create this class: http://alexsears.com/article/adding-roles-to-laravel-users. I created a controller next as follows:
class WelcomeController extends Controller
{
public function welcomeAction()
{
$user = User::find(Auth::user()->id);
$result = $user->hasAnyRoles();
return Response::make("Result: ".$result);
}
}
I'm able to successfully login to the system, routes are working as intended, the variable $user is correctly initialized and I can get all the information out of it (username, id, email, etc.) but once I call the $user->hasAnyRoles() method I get:
BadMethodCallException
Call to undefined method Illuminate\Database\Query\Builder::hasAnyRoles()
If I comment out the respective line in the controller it all works but I cannot call any method of that model without getting that error. Any ideas why this is happening?
As stupid as it is, it turns out that the application was reading the User class from a different file. I had a User_backup.php copied in the same directory just in case and this was the file that the class was read from so any changes to User.php were disregarded. I had to remove the backup file and do a composer update in order to get it all working correctly..

Categories