Parameter count error when using #can Blade directive - php

I'm having the following error when I try to check a permission using policies:
Too few arguments to function App\Policies\AnswerPolicy::view(), 1 passed in /Users/georgio/Projects/Laravel/municipality-app/vendor/laravel/framework/src/Illuminate/Auth/Access/Gate.php on line 710 and exactly 2 expected (View: /Users/georgio/Projects/Laravel/municipality-app/resources/views/layouts/loggedin.blade.php)
AnswerPolicy
<?php
namespace App\Policies;
use App\Answer;
use App\User;
use Illuminate\Auth\Access\HandlesAuthorization;
class AnswerPolicy
{
use HandlesAuthorization;
public function view(User $user, Answer $answer)
{
return true;
}
public function edit(User $user)
{
return true;
}
public function create(User $user)
{
return true;
}
public function delete(User $user)
{
return true;
}
public function update(User $user)
{
return true;
}
}
AnswersController
<?php
namespace App\Http\Controllers;
use App\Question;
use App\Answer;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class AnswersController extends Controller
{
public function index()
{
$this->authorize('view');
return view('answers.show')->with('questions', Question::all());
}
public function create($questionId)
{
$this->authorize('view-submit-answer');
return view('answers.create')->with('question',Question::find($questionId));
}
public function store()
{
$this->authorize('');
$this->validate(request(),[
'answer' => 'required',
]);
$data = request()->all();
$answer = new Answer();
$answer->answer = $data['answer'];
$answer->question_id = $data['question_id'];
$answer->user_id = Auth::id();
$answer->save();
return redirect('/questions/answers');
}
public function edit($answerId)
{ $this->authorize('view-edit-answer');
return view('answers.edit')->with('answer', Answer::find($answerId));
}
public function update($answerId)
{
$this->validate(request(),[
'answer' => 'required',
]);
$data = request()->all();
$answer = Answer::find($answerId);
$answer->answer = $data['answer'];
$answer->save();
return redirect('/answers-question');
}
public function destroy($questionID)
{
$this->authorize('delete-answer');
$answer = Answer::where('question_id', $questionID)->where('user_id', Auth()->id());
$answer->delete();
return redirect('/questions/answers');
}
}
loggedin.blade.php
This is only the part of my code that is causing the error
#can('view', App\Answer::class)
<li>
<a href="/questions/answers">
<span><i class="fa fa-pencil"></i></span>
<span>Answer Question</span>
</a>
</li>
#endcan
I even tried replacing $answer with App\Answer::class and I still had the exact same error.
You can check the full error stack at:
https://flareapp.io/share/xPQQQXP1#F66

The documentation says
When defining policy methods that will not receive a model instance, such as a create method, it will not receive a model instance. Instead, you should define the method as only expecting the authenticated user
I don't see an Answer instance inside your #can statement there. Does one exist? If so, you should be doing this:
#can('view', $answer)
Or, if one doesn't exist at that point, define your method like this
public function view(User $user)
And call it like this:
#can('view', \App\Answer::class)

Related

The get () function not working on laravel 8 updated version

This is the ArticlesController code
<?php
namespace App\Http\Controllers;
use App\Models\Article;
use Illuminate\Http\Request;
class ArticlesController extends Controller
{
public function index()
{
$articles = Article::latest()->get();
return view('articles.index', ['articles' => $articles]);
}
public function show($id)
{
$article = Article::find($id);
return view('articles.show', ['article' => $article]);
}
}
And this is the web.php code
Route::get('/articles', 'App\Http\Controllers\ArticlesController#index');
and this is the layout.blade.php code
<li class={{Request::path() === 'articles' ? 'current_page_item' : ''}}><a href="/articles"
accesskey="4"
I tried so many different ways and it's working but in laravel 8 it's not.
public function index()
{
$articles = Article::query()->latest()->get();
return view('articles.index', ['articles' => $articles]);
}

Laravel Passport Create APIToken undefind function createToken

I am Having this error in my code
Undefined function 'App\Http\Controllers\api\createToken'.intelephense(1010)
i have done all the necessary imports needed to use passport so that i can generate apiTokens but it does not work for me
i will really appreciate it if i can get some one to help me in fixing this error thanks in advance
<?php
namespace App\Http\Controllers\api;
use App\Http\Controllers\Controller;
use App\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
class authController extends Controller
{
public function signup(Request $request)
{
//
$rules=[
'name'=>'required|max:55',
'email'=>'required|email|unique:users',
'password'=>'required',
// 'password_confirm'=>'required',
];
// $valid = $request->validate($rules);
$valid = Validator::make($request->all(),$rules);
if($valid->fails()){
return response()->json(
$valid->errors(),400
);
}else{
$user = User::create($request->all());
$accessToken = $user-createToken('authToken')->accessToken;
return response()->json(['user'=>$user,'accessToken'=>$accessToken], 201);
}
}
public function login()
{
//
}
public function logout(Request $request)
{
//
}
public function user(Request $request)
{
$request->user()->token()->revoke(); return response()->json([
'message' => 'Successfully logged out'
]);
}
public function edit($id)
{
//
}
public function update(Request $request, $id)
{
//
}
public function destroy($id)
{
//
}
}
Sorry Guys it was a typo in the code
$user-createToken('authToken')->accessToken;
i left out the '>' character
$user->createToken('authToken')->accessToken;

Call to undefined relationship [user_id] on model [App\User]

I'm trying Laravel 5.4 (i usually work with 5.1) and im actually copypasting most of the code, so i dont understand what is the trouble, maybe is because there is a better way to do it but yeah, its been 1 hour and i cant get past this;
Hope you can help me with this..
In case this isn't enough i'll be posting my views and routes. Thank to everyone.
This is my Model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
protected $fillable = ['user_id', 'user_name', 'user_birthday'];
public static $rules = [
'user_name' => 'required|max:255',
'user_birthday' => 'required'
];
public $timestamps = false;
}
Controller:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\User;
class UsersController extends Controller
{
public function index()
{
$users = User::with('user_id')->orderBy('user_id', 'ASC')->paginate(10);
return view('admin.users.index')->with("user", $users);
}
public function create()
{
return view('admin.users.create');
}
public function store(Request $request)
{
$users = new User($request->all());
$users->save();
return redirect()->route('admin.users.index');
}
public function show($id)
{
$users = User::find($id);
}
public function edit($id)
{
$users = User::find($id);
return view('admin.users.edit')->with('user', $user);
}
public function update(Request $request, $id)
{
$users = User::find($id);
$users->user_name = $request->user_name;
$users->user_birthday = $request->user_birthday;
$users->save();
return redirect()->route('admin.users.index');
}
public function destroy($id)
{
$users = User::find($id);
$users->delete();
return redirect()->route('admin.users.index');
}
}
Your error is from the following line of code. When you use with on a model is to load children relationships or sub-models. That is why the application is looking for the relationship user_id in the User Model thinking that it's a sub-model of the User model but it's not, so it return an error.
wrong
$users = User::with('user_id')->orderBy('user_id', 'ASC')->paginate(10);
correct
$users = User::orderBy('user_id', 'ASC')->paginate(10);

Using a policy's this->authorize() check in a laravel controller inside a store() method

So I was reading about using laravel policies for granting authorities on the resources of my application but there seems to be a problem there though I followed the tutorial.
I have a user model which can't be created via HTTP requests except by other users who have the Entrust role of 'Admin' or 'Broker'. What I understood and succeeded to make it work on other actions like indexing users was the following:
Inside the AuthServiceProvider.php inside the private $policies array, I registered that User class with the UserPolicy class like that
class AuthServiceProvider extends ServiceProvider {
protected $policies = [
'App\Model' => 'App\Policies\ModelPolicy',
User::class => UserPolicy::class,
Insured::class => InsuredPolicy::class
];
public function boot(GateContract $gate)
{
$this->registerPolicies($gate);
}
}
Define the UserPolicy controller class:
class UserPolicy {
use HandlesAuthorization;
protected $user;
public function __construct(User $user) {
$this->user = $user;
}
public function index(User $user) {
$is_authorized = $user->hasRole('Admin');
return $is_authorized;
}
public function show(User $user, User $user_res) {
$is_authorized = ($user->id == $user_res->id);
return $is_authorized;
}
public function store() {
$is_authorized = $user->hasRole('Admin');
return $is_authorized;
}
}
Then inside the UserController class, before performing the critical action I use this->authorize() check to halt or proceed depending on the privilege of the user
class UserController extends Controller
{
public function index()
{
//temporary authentication here
$users = User::all();
$this->authorize('index', User::class);
return $users;
}
public function show($id)
{
$user = User::find($id);
$this->authorize('show', $user);
return $user;
}
public function store(Request $request) {
$user = new User;
$user->name = $request->get('name');
$user->email = $request->get('email');
$user->password = \Hash::make($request->get('password'));
$this->authorize('store', User::class);
$user->save();
return $user;
}
}
The problem is that $this->authorize() always halts the process on the store action returning exception: This action is unauthorized.
I tried multiple variations for arguments of the authorize() and can't get it to work like the index action
In store() function of UserPolicy::class you are not passing the User model object:
public function store(User $user) {
$is_authorized = $user->hasRole('Admin');
return true;
}
missing argument User $user.
Maybe this is the cause of the problem.

In laravel view() function within a controller, can this detect an AJAX request

In my controller, I have something like the following:
public function index()
{
$questions = Question::all();
return view('questions.index', compact('questions'));
}
However, I would like this route to also be used by my ajax requests. In which case, I'd like to return JSON. I'm considering the following:
public function index()
{
$questions = Question::all();
return $this->render('questions.index', compact('questions'));
}
public function render($params)
{
if ($this->isAjax()) {
return Response::json($params);
} else {
return view('questions.index')->with($params);
}
}
..by the way, I haven't tested any of this yet, but hopefully you get the idea.
However, I was wondering if I can alter the built in view(...) functionality itself to keep things even lighter. So I just keep the following:
public function index()
{
$questions = Question::all();
// this function will detect the request and deal with it
// e.g. if header X-Requested-With=XMLHttpRequest/ isAjax()
return view('questions.index', compact('questions'));
}
Is this possible?
You probably want to make custom response:
add ResponseServiceProvider.php
namespace App\Providers;
use Request;
use Response;
use View;
use Illuminate\Support\ServiceProvider;
class ResponseServiceProvider extends ServiceProvider
{
/**
* Perform post-registration booting of services.
*
* #return void
*/
public function boot()
{
Response::macro('smart', function($view, $data) {
if (Request::ajax()) {
return Response::json($data);
} else {
return View::make($view, $data);
}
});
}
/**
* Register any application services.
*
* #return void
*/
public function register()
{
//
}
}
Add 'App\Providers\ResponseServiceProvider' to providers list in config/app.php:
'providers' => [
'App\Providers\ResponseMacroServiceProvider',
];
Use new helper in controller:
return Response::smart('questions.index', $data);
Simply check if the Request is an Ajax request in your index method itself.
public method index() {
$questions = Question::all();
if(\Request::ajax())
return \Response::json($questions);
else
return view('questions.index', compact('questions'));
}
Use Request::ajax(), or inject the request object:
use Illuminate\Http\Request;
class Controller {
public function index(Request $request)
{
$data = ['questions' => Question::all()];
if ($request->ajax()) {
return response()->json($data);
} else {
return view('questions.index')->with($data);
}
}
}
Your view should never know anything about the HTTP request/response.
I guess the simple method is just to put a method inside the parent Controller class:
use Illuminate\Routing\Controller as BaseController;
abstract class Controller extends BaseController {
...
protected function render($view, $data)
{
if (Request::ajax()) {
return Response::json($data);
} else {
return view($view, $data);
}
}
}
and then instead of doing view('questions.index, $data);, do $this->render('questions.index', $data);

Categories