Why is my laravel policy authorization not working after a while - laravel

I'm following the laracasts 5.7 series and I was working on the authorization part using policies. It was working fine when I first added it. But the next day when I opened the app again (without TOUCHING any of the code) I kept being thrown to a 403 error. This happened the two times already. At first I just thought I messed up the code. So I redid the whole policy authorization again. But the second time, I made sure everything was working fine before I saved my code. And then the same thing happened.
Here's my code so far:
ProjectPolicy.php:
public function touch(User $user, Project $project)
{
return $project->owner_id == $user->id;
}
AuthServiceProvider.php:
class AuthServiceProvider extends ServiceProvider
{
/**
* The policy mappings for the application.
*
* #var array
*/
protected $policies = [
// 'App\Model' => 'App\Policies\ModelPolicy',
'App/Project' => 'App\Policies\ProjectPolicy',
];
/**
* Register any authentication / authorization services.
*
* #return void
*/
public function boot()
{
$this->registerPolicies();
//
}
}
web.php:
Route::resource('projects', 'ProjectsController')->middleware('can:touch,project');
ProjectsController.php:
use App\Project;
use Illuminate\Http\Request;
class ProjectsController extends Controller
{
public function __construct() {
$this->middleware('auth');
}
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$projects = Project::where('owner_id', auth()->id())->get();
return view('projects.index', ['projects' => $projects]);
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
return view('projects.create');
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$validated = request()->validate([
'title' => 'required',
'description' => ['required','min:5']
]);
$validated['owner_id'] = auth()->id();
Project::create($validated);
return redirect('/projects');
}
/**
* Display the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function show(Project $project)
{
// $this->authorize('update', $project);
// abort_if($project->owner_id !== auth()->id(), 403);
// $this->authorize('touch', $project); // from ProjectPolicy
// abort_if( \Gate::denies('touch', $project), 403);
return view('projects.show', ['project' => $project]);
}
/**
* Show the form for editing the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function edit(Project $project)
{
return view('projects.edit', ['project' => $project]);
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param int $id
* #return \Illuminate\Http\Response
*/
public function update(Project $project)
{
$project->update(request(['title','description']));
return redirect()->action(
'ProjectsController#show', ['id' => $project->id]
);
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function destroy(Project $project)
{
$project->delete();
return redirect('/projects');
}
}
To be clear: It was working the night before, and the next day when I opened the app it kept throwing me to a 403 error even when I didn't edit the code at all. I don't know what's happening at all.

Related

I want to do pagination, but its not working Method Illuminate\Database\Eloquent\Collection::links does not exist

Controller:
this is the whole controller code
<?php
namespace App\Http\Controllers;
use App\Exam_sched;
use App\Subject;
use App\Batch;
use Session;
use Illuminate\Http\Request;
class ExamSchedController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
class ExamSchedController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$exam_scheds= Exam_sched::paginate(3);
return view('examschedule',compact('exam_scheds'));
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
$exam_scheds=Exam_sched::all();
$subjects=Subject::all();
$batches=Batch::all();
return view('examschedule', compact('exam_scheds','subjects','batches'));
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$request->validate([
"date"=>"required",
"subject_id"=>"required",
"batch_id"=>"required",
"roomNo"=>"required",
"startTime"=>"required",
"endTime"=>"required"
]);
// $rules= array(
// "date"=>"required",
// "subject_id"=>"required",
// "batch_id"=>"required",
// "roomNo"=>"required",
// "startTime"=>"required",
// "endTime"=>"required"
// );
// $this->validate($request, $rules);
$exam_sched= new Exam_sched;
$exam_sched->date=$request->date;
$exam_sched->subject_id=$request->subject_id;
$exam_sched->batch_id=$request->batch_id;
$exam_sched->roomNo=$request->roomNo;
$exam_sched->startTime=$request->startTime;
$exam_sched->endTime=$request->endTime;
$exam_sched->save();
Session::flash("message","New Schedule has been added");
return redirect('/examschedule');
}
/**
* Display the specified resource.
*
* #param \App\Exam_sched $exam_sched
* #return \Illuminate\Http\Response
*/
public function show(Exam_sched $exam_sched)
{
//
}
/**
* Show the form for editing the specified resource.
*
* #param \App\Exam_sched $exam_sched
* #return \Illuminate\Http\Response
*/
public function edit($id)
// public function edit()
{
$exam_sched = Exam_sched::find($id);
$subjects=Subject::all();
$batches=Batch::all();
return view('editschedule',compact('exam_sched','subjects','batches'));
// return view('examschedule');
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param \App\Exam_sched $exam_sched
* #return \Illuminate\Http\Response
*/
// public function update(Request $request, Exam_sched $exam_sched)
public function update(Request $request, $id)
{
$exam_sched= Exam_sched::find($id);
$rules= array(
"date"=>"required",
"subject_id"=>"required",
"batch_id"=>"required",
"roomNo"=>"required",
"startTime"=>"required",
"endTime"=>"required"
);
$this->validate($request, $rules);
$exam_sched= Exam_sched::find($id);
$exam_sched->date=$request->date;
$exam_sched->batch_id=$request->batch_id;
$exam_sched->subject_id=$request->subject_id;
$exam_sched->roomNo=$request->roomNo;
$exam_sched->startTime=$request->startTime;
$exam_sched->endTime=$request->endTime;
$exam_sched->save();
Session::flash("message","Schedule has been updated!");
return redirect('/examschedule');
}
/**
* Remove the specified resource from storage.
*
* #param \App\Exam_sched $exam_sched
* #return \Illuminate\Http\Response
*/
public function delete($id)
{ $exam_sched= Exam_sched::find($id);
$schedToRemove=Exam_sched::find($id);
$schedToRemove->delete();
// Session::flash("message","Successfully Deleted!");
return redirect('/examschedule')->with('success','Data Deleted');
}
}
Route:
Route::get('/examschedule', 'ExamSchedController#index');
View Blade:
<tbody>
#if($exam_scheds->count())
#foreach($exam_scheds as $exam_sched)
<tr class="tbody">
<td>{{$exam_sched->date}}</td>
<td>{{$exam_sched->batch->name}}</td>
<td>{{$exam_sched->subject->name}}</td>
<td>{{$exam_sched->roomNo}}</td>
<td>{{$exam_sched->startTime}}</td>
<td>{{$exam_sched->endTime}}</td>
<td>{{$exam_sched->created_at->diffForHumans()}}</td>
</tr>
#endforeach
#endif
</tbody>
</table>
{{ $exam_scheds->links() }}
Method Illuminate\Database\Eloquent\Collection::links does not exist.
Please help me ,I'm new in laravel
thanks in advance
Ok, now I see the problem.
In index method of controller you use
$exam_scheds= Exam_sched::paginate(3);
but in create method you use:
$exam_scheds=Exam_sched::all();
and you use same view in those 2 methods.
Of course when you use all() method there is no pagination so you cannot use links then in view.
So probably you should change in create method to also paginate same as in index method.

I am a beiggner in Laravel. How can we fix this?

I am a beginner, building a bulletin board using Laravel.
I got this error:
Class 'LaravelForum\Http\Controllers\Discussion' not found
>
public function index()
> {
>
> return view('discussions.index', [
> 'discussions' => Discussion::paginate(5)
> ]);
>
> // $discussions = Discussion::paginate(5);
>
> // return view('discussions.index');
>
> }
>
> /**
> * Show the form for creating a new resource.
> *
> * #return \Illuminate\Http\Response
> */
> public function create()
> {
> //
> return view('discussions.create');
> }
>
> /**
> Arguments
> "Class 'LaravelForum\Http\Controllers\Discussion' not found"
This is the content of the file in question:
C:\laravel-apps\bulletin-board\app\Http\Controllers\DiscussionsController.php
<?php
namespace LaravelForum\Http\Controllers;
use Illuminate\Http\Request;
use LaravelForum\Http\Requests\CreateDiscussionRequest;
class DiscussionsController extends Controller
{
public function __construct()
{
$this->middleware('auth')->only(['create', 'store']);
}
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
return view('discussions.index', [
'discussions' => Discussion::paginate(5)
]);
// $discussions = Discussion::paginate(5);
// return view('discussions.index');
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
//
return view('discussions.create');
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(CreateDiscussionRequest $request)
{
//
auth()->user()->discussions()->create([
'title' => $request->title,
'content' => $request->content,
'channel_id' => $request->channel,
'slug' => str_slug($request->title),
]);
session()->flash('success', 'Discussin posted .');
return redirect()->route('discussion.index');
}
/**
* 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)
{
//
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param int $id
* #return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
//
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function destroy($id)
{
//
}
}
C:\laravel-apps\bulletin-board\app\Http\Controllers\HomeController.php
<?php
namespace LaravelForum\Http\Controllers;
use Illuminate\Http\Request;
class HomeController extends Controller
{
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('auth');
}
/**
* Show the application dashboard.
*
* #return \Illuminate\Contracts\Support\Renderable
*/
public function index()
{
return view('home');
}
}
In your DiscussionsController add this line at the use section.
use LaravelForum\Discussion;
add this line in Your DiscussionsController
use LaravelForum\Discussion;

Laravel, Show(), Edit (), update functions not working

In the code below methods show, edit update are not working.
<?php
namespace App\Http\Controllers\admins;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\contact;
use Image;
use Auth;
use Storage;
use File;
class ContactController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$contact = Contact::orderby('created_at', 'desc')->paginate(5);
//$agent=Agent::orderby('id','desc')->paginate(5);
return view('admin.messages.index', ['contacts' => $contact]);
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
return back()->with('success', 'Message can only be created by Users end.');
}
/** * Display the specified resource.
*
* #param \App\contact $contact
* #return \Illuminate\Http\Response
*/
public function show(contact $contact)
{
dd(['contact' => $contact]);
//return back()->with('success','Message Contents Are Already Shown');
}
/**
* Show the form for editing the specified resource.
*
* #param \App\contact $contact
* #return \Illuminate\Http\Response
*/
public function edit(contact $contact)
{
return view('admin.messages.edit', compact('contact'));
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param \App\contact $contact
* #return \Illuminate\Http\Response
*/
public function update(Request $request, contact $contact)
{
dd($request);
}
/**
* Remove the specified resource from storage.
*
* #param \App\contact $contact
* #return \Illuminate\Http\Response
*/
public function destroy(contact $contact)
{
return back()->with('success', 'Message history can not be Deleted. ');
}
}
Assuming you are using a slug in a route like contacts/{ slugĀ }
public function show(contact $contact)
{
dd(['contact' => $contact]);
//return back()->with('success','Message Contents Are Already Shown');
}
Receives an id not a contact... you are initializing/declaring in the function parameter as contact thats why it somehow gets casted to a contact... but it's an id you should do something like:
public function show($id)
{
$contact = Contact::findOrFail($id);
dd(['contact' => $contact]);
//return back()->with('success','Message Contents Are Already Shown');
}

Laravel 5.5, Default route for index not working for resource controller

I have a resource Controller named CmsPagesController,
class CmsPagesController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
return 'something';
// $pages=CmsPages::all();
// return view('backend.pages.cms.list')->with('pages',$pages);
}
public function list(){
return '123';
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
return view('backend.pages.cms.add');
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$this->validate($request, [
'name' => 'required',
'slug' => 'required',
'description'=> 'required'
]);
$Page=new CmsPages;
$Page->name= $request->input('name');
$Page->slug= $request->input('slug');
$Page->description= $request->input('description');
$Page->copyright= $request->input('copyright');
$Page->keywords= $request->input('keywords');
$Page->save();
return redirect('/admin/pages')->with('success','Page Added Successfully');
}
/**
* 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)
{
//
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param int $id
* #return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
//
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function destroy($id)
{
//
}
}
My Add function and store function is working perfect, I can render add page and can store data to database but my index function is not working, I have placed a sample return statement but that is not executed as well. what am I missing
Following is my route
Route::resource('pages','CmsPagesController');
I was facing the same issue, that is index function wasn't returning anything, not even any error.
I had a UsersController made as a resource.
And route as:
Route::resource('users', 'UsersController');
When you try to hit the following URL
...public/users/index
it won't return anything.
It worked for me when I tried
...public/users
the index function is automatically called. You don't have have to write /index in the the url.

ErrorException in SessionGuard.php | Getting error when trying to register user while creating new order

I want user to register and also buy a package. To do that I took input for registration details and package details. Now when I'm processing order to save package details in session and register, I get this error : Argument 1 passed to Illuminate\Auth\SessionGuard::login() must be an instance of Illuminate\Contracts\Auth\Authenticatable, instance of Illuminate\View\View given, called in C:\xampp\htdocs\rename\app\Traits\OrderRegister.php on line 63 and defined. I'm using an trait to register user and return back to function when registration is complete.
OrderController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Package;
use App\ListingType;
use Illuminate\Support\Facades\Auth;
use App\Order;
use Carbon\Carbon;
use App\Traits\OrderRegister;
class OrderController extends Controller
{
use OrderRegister;
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index($type)
{
$listingtype = ListingType::where('type', '=', $type)->first();
if ($listingtype) {
$packages = $listingtype->packages()->get();
return view('packages.index', compact('packages'));
}
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create($id)
{
$package = Package::where('id', '=', $id)->first();
if (Auth::check()) {
return view('order.create_loggedin', compact('package'));
}
else {
return view('order.create_register', compact('package'));
}
}
/**
* Process a new order request. Store order values in session.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function process(Request $request)
{
$order = ['package_id' => $request->package_id, 'order_qty' => $request->no_of_listing];
session(['order' => $order]);
if (Auth::guest()) {
return $this->register($request); // need to check session for orders available in OrderRegister trait.
}
return $this->store($request);
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
if($request->session()->has('order')) {
$package = Package::where('id', '=', $request->package_id )->first();
if($request->user() == Auth::user()) {
for( $n=1;$n<=$request->no_of_listing;$n++) {
$order = new Order;
$order->package_id = $request->package_id;
$order->user_id = Auth::user()->id;
$order->expire_at = Carbon::now()->modify('+'.$package->duration_in_months.' months');
$order->save();
}
return redirect('/');
}
}
}
/**
* 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)
{
//
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param int $id
* #return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
//
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function destroy($id)
{
//
}
}
trait : OrderRegister.php
<?php
namespace App\Traits;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Validator;
trait OrderRegister
{
use RedirectsUsers;
/**
* Get a validator for an incoming registration request.
*
* #param array $data
* #return \Illuminate\Contracts\Validation\Validator
*/
protected function validator(array $data)
{
return Validator::make($data, [
'name' => 'required|max:255',
'email' => 'required|email|max:255|unique:users',
'username' => 'required|max:255|unique:users',
'password' => 'required|min:6|confirmed',
]);
}
/**
* Create a new user instance after a valid registration.
*
* #param array $data
* #return User
*/
protected function create(array $data)
{
$user = User::create([
'name' => $data['name'],
'email' => $data['email'],
'username' => $data['username'],
'password' => bcrypt($data['password']),
]);
$user->profile()->save(new UserProfile);
return $user;
}
/**
* Execute the job.
*
* #return void
*/
public function register(Request $request)
{
$validator = $this->validator($request->all());
if ($validator->fails()) {
$this->throwValidationException(
$request, $validator
);
}
Auth::guard($this->getGuard())->login($this->create($request->all()));
return $this->store($request);
}
/**
* Get the guard to be used during registration.
*
* #return string|null
*/
protected function getGuard()
{
return property_exists($this, 'guard') ? $this->guard : null;
}
}
I could not find any solution for this error so created my own thread for the first time please someone help.
It throws an error because you are trying to login a vue.
in your OrderController.php you are using create method which return a view.
this method will override the create method on your trait.
So you have something like this :
Auth::guard($this->getGuard())->login(/* A view */);
you can at least rename the method on the trait from create to createUser for example.
then you call it from the guard like this :
Auth::guard($this->getGuard())->login($this->createUser($request->all()));

Resources