should be compatible with App\Http\Controllers\Controller::authorize($ability, $arguments = Array) - register controller error - laravel

I'm trying to send the form information to database but when i submit the form this error appears:
ErrorException
Declaration of App\Http\Controllers\LivroController::authorize() should be compatible with App\Http\Controllers\Controller::authorize($ability, $arguments = Array)
CONTROLLER (LivroController)
<?php
namespace App\Http\Controllers;
use App\Http\Requests\StoreUpdateLivro;
use Illuminate\Support\Facades\Auth;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\Livro;
class LivroController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
protected $request;
private $repository;
private $livro;
public function __construct(Livro $livro)
{
$this->livro = $livro;
}
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public function authorize()
{
return true;
}
/* public function index()*/
// {
/* $title = 'listagem dos livros';
$livros = $this->livro->all();
return view ('livros/cadastro', compact('livros','title'));*/
// return view ('livros/cadastro');
// }
protected function validator(Request $request)
{
return Validator::make($request, [
'namel' => ['required', 'string', 'max:200'],
'autor' => ['required', 'string', 'email', 'max:200'],
'editora' => ['required', 'string', 'max:50'],
'categoria'=> ['required', 'string', 'min:50'],
'classificação'=> ['required', 'string', 'min:1','max:2'],
'descricao'=> ['required', 'string', 'min:200'],
'image'=> ['not required'],
]);
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function create(StoreUpdateLivro $request)
{
$user = Auth::user()->id;
$data = $request->all();
if($request->image->isValid()){
$image = $request->image->store('livros');
$data['image'] = $image;
}
Livro::create([
'users_id' => $user,
'namel' => $request['namel'],
'autor' => $request['autor'],
'editora' => $request['editora'],
'categoria'=> $request['categoria'],
'classificação'=>$request['classificação'] ,
'descricao'=>$request['descricao'],
'image'=>$request['image'],
]);
return view('livros/cadastro');
}
public function index()
{
$livro = DB::select('select * from livros');
return view('livros/mostrar_livros', [
'livro' => $livro,
]);
}
}

Remove authorize() method from LivroController and then,
go to StoreUpdateLivro file and set return true into authorize() method.
and also you don't need to validator method in your controller.
See more about the FormRequest in Laravel.

I think, you have a copy/paste problem
Delete LivroController:: authorize() method - you copied it from Form Request - and all will be work fine.

Related

The email has already been taken [duplicate]

This question already has answers here:
Laravel: Validation unique on update
(33 answers)
Closed 10 months ago.
I'm going to edit a row using form request validate laravel, but when editing if I do not change the email, The email has already been taken error. Gives
this is from request validate EditAdmin
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rules;
use Illuminate\Validation\Rule;
class EditAdmin extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
return [
'name' => ['required', 'string'],
'email' => ['required', 'string', 'email', Rule::unique('admins')],
'password' => ['required', 'confirmed', Rules\Password::defaults()],
];
}
}
this my controller AdminController
<?php
namespace App\Http\Controllers;
use App\Repositories\AdminRepository;
use App\Http\Requests\CreateAdmin;
use App\Interfaces\AdminInterface;
use App\Http\Requests\EditAdmin;
use Illuminate\Validation\Rules;
use Illuminate\Validation\Rule;
use Illuminate\Http\Request;
use App\Models\Admin;
class AdminController extends Controller
{
/**
* admin Service Interface
* #var AdminRepository
*/
protected $admin;
/**
* Inject service By Service Container
* #param AdminRepository $admin
*/
public function __construct(AdminRepository $admin)
{
$this->admin = $admin;
}
/**
* Show All Admins
* Method:get
* Return get All admin
* #return \Illuminate\Contracts\View\View
*/
public function getAllAdmin():\Illuminate\Contracts\View\View
{
$admins = $this->admin->getAllAdmin();
return view('admin.list',['admins'=>$admins]);
}
/**
* param:Admin_id
* method delete
* Delete admin
* #param int $id
* #return \Illuminate\Http\RedirectResponse
*/
public function deleteAdmin(int $id):\Illuminate\Http\RedirectResponse
{
$this->admin->deleteAdmin($id);
return redirect('/admins');
}
/**
* get single admin
* method get
* #param $id
* #return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View
*/
public function getAdmin(int $id):\Illuminate\Contracts\View\View
{
$admin = $this->admin->getAdmin($id);
return view('admin.edit',['admin'=>$admin]);
}
/**
* Updated Admin
* Route:Api/Nft/$nft_id
* Method:Put
* #param Request $request
* #return \Illuminate\Contracts\Foundation\Application|\Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
*/
public function editAdmin(EditAdmin $request):\Illuminate\Http\RedirectResponse
{
$request->validated();
//validate all input
// $request->validate([
// 'name' => ['required', 'string'],
// 'email' => ['required', 'string', 'email', Rule::unique('admins')->ignore($request->id),],
// 'password' => ['required', 'confirmed', Rules\Password::defaults()],
// ]);
$data = $request->all();
$this->admin->editAdmin($data);
return redirect('/admins');
}
/**
* create new admin
* #param CreateAdmin $request
* #return \Illuminate\Contracts\Foundation\Application|\Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
*/
public function createAdmin(CreateAdmin $request):\Illuminate\Http\RedirectResponse
{
$request->validated();
$data = $request->all();
$this->admin->createAdmin($data);
return redirect('/admins');
}
}
How can I fix this bug?
pleas help me!!!
this is because of using same validator for crate and update user . and user own email in update process make trouble for you .
solotion:
1- crate new validator class for edit user << UserEditRequest >>
2- use this code for validate email
'email' => ['required', 'string', 'email,'.auth()->user()->id,]

I have an idea to use auth middleware to retrieve a user's products

i have an idea to use auth middleware to retrieve a user's products but currently i am not able to retrieve that user's products. Instead, it listed all the products of other users. Can you guys give me some ideas to help me complete it. Thank you !!!
This is my ProjectController code:
<?php
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use App\Http\Resources\ProjectResource;
use App\Models\Project;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
class ProjectController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$projects = Project::all();
return response([
'projects' => ProjectResource::collection($projects),
'message' => 'Retrieved successfully'
], 200);
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$data = $request->all();
$validator = Validator::make($data, [
// 'uuid' => 'required|unique:projects',
'user_id' => 'required',
'name' => 'required|max:255',
'status' => 'required',
]);
if ($validator->fails()) {
return response(['error' => $validator->errors(), 'Validation Error']);
}
$projects = Project::create($data);
return response(['projects' => new ProjectResource($projects), 'message' => 'Created successfully'], 201);
}
/**
* Display the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function show(Project $project)
{
return response(['project' => new ProjectResource($project), 'message' => 'Retrieved successfully'], 200);
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param int $id
* #return \Illuminate\Http\Response
*/
public function update(Request $request, Project $project)
{
$project->update($request->all());
return response(['project' => new ProjectResource($project), 'message' => 'Update successfully'], 200);
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function destroy(Project $project)
{
$project->delete();
return response(['message' => 'Deleted'], 204);
}
}
This is my ProjectModel code:
<?php
namespace App\Models;
use App\Enums\ProjectStatus;
use App\Http\Traits\Uuid;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Str;
class Project extends Model
{
use HasFactory;
use Uuid;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name',
'status',
'user_id',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'id',
'uuid',
];
protected $cast = [
'status' => ProjectStatus::class
];
public function setUuidAttribute()
{
$this->attributes['uuid'] = Str::uuid();
}
}
This is my API Router code:
You have to retrieve the user first in order to filter the products. There are multiple ways to do that. Here's a link to Laravel's documentation on the subject: https://laravel.com/docs/8.x/authentication#retrieving-the-authenticated-user
You also have to filter your query (your query being Project::all()) so that it only retrieves the products for the user. Here's a link to some Laravel documentation related to that: https://laravel.com/docs/8.x/eloquent#retrieving-models
In the end, replacing this $projects = Project::all(); with this $projects = Project::where('user_id', auth()->user()->id); should do the trick.
Try this
public function index()
{
$projects = Project::where('user_id', auth()->id())->get();
return response([
'projects' => ProjectResource::collection($projects),
'message' => 'Retrieved successfully'
], 200);
}

Merge Form Request Validation for store and update

I am using Request validation to validate the user's input.
This is UpdateUser:
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Gate;
class UpdateUser extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public function authorize()
{
return Gate::allows('update-user');
}
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
$user_id = Arr::get($this->request->get('user'), 'id');
return [
'user.firstname' => 'required|string|max:255',
'user.lastname' => 'required|string|max:255',
'user.email' => "required|string|email|max:255|unique:users,email,{$user_id}",
'user.password' => 'sometimes|nullable|string|min:4|confirmed',
];
}
}
As you can see, there is some update-specific stuff happening:
The authorize() method checks whether the user is allowed to update-user and inside the rules I am excluding the row of the current user from being unique:
'user.email' => "required|string|email|max:255|unique:users,email,{$user_id}",
As I would like to merge UpdateUser and StoreUser, what would be the most efficient and readable way to determine, whether I am updating or saving?
This is my current approach:
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Gate;
class UpdateUser extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public function authorize()
{
if($this->isUpdating())
{
return Gate::allows('update-user');
}
return Gate::allows('create-user');
}
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
if($this->isUpdating()){
$user_id = Arr::get($this->request->get('user'), 'id');
return [
...
];
}
return [];
}
/**
* #return bool
*/
protected function isUpdating(){
return $this->isMethod('put') || $this->isMethod('patch');
}
}
I am wondering if I may extend the FormRequest class and provide isUpdating() by default.
Your update and store method are not the same request type, you have PUT and PATCH method on your request instance, so you can check the request type as like :
switch ($request->method()) {
case 'PATCH':
// do anything in 'patch request';
break;
case 'PUT':
// do anything in 'put request';
break;
default:
// invalid request
break;
}
I learnt about a new approach to validation some time ago using separate validator class and I kinda like it a lot. Let me show you
Create a directory Validators and a class inside UserValidator
class UserValidator
{
public function rules(User $user)
{
return [
'user.firstname' => [
'required',
'string',
'max:255',
],
'user.lastname' => [
'required',
'string',
'max:255',
],
'user.email' => [
$user->exists ? 'sometimes' : null,
'required',
'string',
'email',
'max:255',
Rule::unique('users', 'email')->ignore($user->exists ? $user->id : null)
],
'user.password' => [
$user->exists ? 'sometimes' : null,
'required',
'string',
'min:8'
],
];
}
public function validate(array $data, User $user)
{
return validator($data, $this->rules($user))
//->after(function ($validator) use ($data, $user) {
// Custom validation here if need be
//})
->validate();
}
}
Then authorization can be done in Controller
class UserController
{
use AuthorizesRequests;
/**
* #param Request $request
*/
public function store(Request $request)
{
$this->authorize('create_user', User::class);
$data = (new UserValidator())->validate(
$request->all(),
$user = new User()
);
$user->fill($data)->save();
}
/**
* #param Request $request
* #param \App\user $user
*/
public function update(Request $request, User $user)
{
$this->authorize('update_user', $user);
$data = (new UserValidator())->validate(
$request->all(),
$user
);
$user->fill($data)->save();
}
}
This was proposed and explained by (twitter handle) #themsaid

How to use the ignore rule in Form Request Validation

this is PostsRequest.php in http/request:
<?php
namespace App\Http\Requests;
use App\Post;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;
class PostsRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
return [
'title' => ['required','max:255', Rule::unique('posts')->ignore($this->id)],
'slug' => ['required', Rule::unique('posts')->ignore($this->id),],
'content' => 'required',
'type' => 'required|in:blog,download,page',
'status' => 'required',
];
}
}
and this is edit() method in PostController.php
public function update(PostsRequest $request, $id)
{
$validated = $request->validated();
$validated['user_id'] = auth()->user()->id;
$post = Post::find($id)->fill($validated);
$post->save();
return redirect()->action('PostController#index');
}
Problem: show error in update page that this value is already exists.
who to resolve problem unique fields in edit form?
Problem Solved
change:
Rule::unique('posts')->ignore($this->route('id'))
with:
Rule::unique('posts')->ignore($this->route('post'))
If you're wanting to resolve the $id from the route then you can use the route() method in your request class e.g.
Rule::unique('posts')->ignore($this->route('id'))

Showing posts from specific user in Laravel

I have a question about showing posts from specific user. I'm building a basic keeping records website for my brothers company. I made a redirected login for normal users(workers in company) and for admin(company manager). So I'm new at Laravel and programming, a did everything for this website and all I need is how to show posts on admin profile for specific user. On admin profile I'll make pages for all workers profiles and on specific page I need to show posts for that specific user. How can I do that? Making new Controller?
<?php
namespace App\Http\Controllers;
use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;
use App\Post;
class PostsController extends Controller
{
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('auth');
}
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$post = Post::all();
return view('posts.tabela')->with('posts', $post);
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
return view('posts.create');
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$this->validate($request, [
'br_kesice' => 'required',
'ime' => 'required',
'br_telefona' => 'required',
'posao' => 'required',
'cijena' => 'required',
'placanje' => 'required',
'popust' => 'required',
'datum_preuz' => 'required',
'datum_izdav' => 'required',
'smjena' => 'required',
'radnik' => 'required',
'status' => 'required'
]);
$post = new Post;
$post->br_kesice = $request->input('br_kesice');
$post->ime = $request->input('ime');
$post->br_telefona = $request->input('br_telefona');
$post->posao = $request->input('posao');
$post->cijena = $request->input('cijena');
$post->placanje = $request->input('placanje');
$post->popust = $request->input('popust');
$post->datum_preuz = $request->input('datum_preuz');
$post->datum_izdav = $request->input('datum_izdav');
$post->smjena = $request->input('smjena');
$post->radnik = $request->input('radnik');
$post->status = $request->input('status');
$post->user_id = auth()->user()->id;
$post->save();
return redirect('/home');
}
/**
* Display the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function show($id)
{
//
}
/**
* Show the form for editing the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function edit($id)
{
$post = Post::find($id);
if(auth()->user()->id !==$post->user_id){
return redirect('/posts')->with('error', 'Nedozvoljen pristup!');
}
return view('posts.edit', compact('post', 'id'))->with('post', $post);
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param int $id
* #return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
$this->validate($request, [
'br_kesice' => 'required',
'ime' => 'required',
'br_telefona' => 'required',
'posao' => 'required',
'cijena' => 'required',
'placanje' => 'required',
'popust' => 'required',
'datum_preuz' => 'required',
'smjena' => 'required',
'radnik' => 'required',
'status' => 'required'
]);
$post = Post::find($id);
$post->br_kesice = $request->input('br_kesice');
$post->ime = $request->input('ime');
$post->br_telefona = $request->input('br_telefona');
$post->posao = $request->input('posao');
$post->cijena = $request->input('cijena');
$post->placanje = $request->input('placanje');
$post->popust = $request->input('popust');
$post->datum_preuz = $request->input('datum_preuz');
$post->datum_izdav = $request->input('datum_izdav');
$post->smjena = $request->input('smjena');
$post->radnik = $request->input('radnik');
$post->status = $request->input('status');
$post->save();
return redirect('/home');
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function destroy($id)
{
//
}
}
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use App\User;
class Post extends Model
{
protected $table = 'posts';
public $primaryKey = 'id';
public $timestamps = true;
public function user(){
return $this->belongsTo('App\User');
}
}
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use App\Post;
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',
];
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
public function posts(){
return $this->hasMany('App\Post');
}
public function is_admin(){
if($this->admin)
{
return true;
}
return false;
}
}

Resources