Authorization Using Form Requests in Laravel - laravel

Not sure what I am doing wrong here but I am having trouble getting the $id of the post to pass to the form request when checking to see if the person editing owns the post. "Job" would be a job posting. Below is the logic in the JobsRequest.
public function authorize()
{
$job=Job::find($this->id);
if($job->user_id == Auth::user()->id){
return true;
}else{
return false;
}
The above keeps returning as false. The update method in the controller is below
public function update(JobsRequest $request, $id)
{
$job=Job::find($id);
$job_data=$request->all();
$job->update($job_data);
return redirect('/jobs/'.$job->id.'/edit');
}

To grab the id within the FormRequest object, you'd need to use the following...
$id = $this->route('id');

Go to the AuthServiceProvider.php and write
$gate->define('show-product',function($user,$product){
return $user->id==$product->customer_id;
});
Then write your controller
$product= Product::find($id);
Auth::loginUsingId(3);
//Auth::logout();
if(Gate::denies('update',$product)){
App::abort('404','Product Not Found');
}
// $this->authorize('update',$product);
return $product->name;
I think It's working perfectly

Try this, which gets the id from the route parameter.
public function authorize(){
$job_id = $this->route('id');
$job=Job::find($job_id);
$user = $this->user();
if($job->user_id == $user->id) return true;
return false;
}

Thanks for pointing me in the right direction. I got this straight from the docs.. This worked for me.
$jobId = $this->route('jobs');
return Job::where('id', $jobId)
->where('user_id', Auth::id())->exists();

Related

Undefined property: App\Http\Controllers\Api\ApiAuthController::$auth

enter image description here
Im new in Laravel i don't how to figure out the mistake
here is my laravel code:
public function login(Request $request)
{
$gen_user = GenUser::where('username',$request->username)->where('confirmed',0)->first();
if($gen_user){
return response()->json(3);+6
}
if($this->auth->attempt($request->only('username','password'))){
$gen_user = GenUser::join('gen_people','gen_users.gen_person_id','=','gen_people.id')
->where('gen_users.id',\Auth::user()->id)
->select(['gen_people.first_name','gen_people.middle_name','gen_people.last_name','gen_people.first_name','gen_users.id','gen_users.username','gen_users.confirmed'])
->first();
// dd($gen_user);
$gen_user->name = $gen_user->first_name." ".$gen_user->middle_name." ".$gen_user->last_name;
if($gen_user->confirmed == 1){
return response()->json($gen_user);
}elseif($gen_user->confirmed == 2){
return response()->json(2);
}else{
return response()->json(3);
}
}else{
return response()->json(false);
}
}
Can someone help me...thanks in advance...
When you use this keyword you mean refer to exactly current class.but in your that controller there is not any auth method or property.
Create authentication(or if you use passport it make it automaticly) and migrate.
After that you can use
Auth::attempt(['username'=>request('username'),'password'=>request('password')])

If Statement not working properly in Laravel Controller

I have a simple If Statement in my controller that is not triggering properly.
I have the following route:
Route::resource ('/my-health-hub', 'MyHealthHubController');
I have the following in my controller:
public function index(Request $request)
{
$test = Auth::check();
if ($test = false){
return redirect('/login');
} else {
$providers = $request->user()->providers()->get();
return view ('my-health-hub', compact('providers'));
}
}
When a user is logged in, the second part of the If Statement is triggered properly. However, when logged out, the If Statement still tries to trigger the second part of the If Statement. I did dd($test) to verify the value was false when logged out and it was. So, the second part of the statement should not be triggering when user is logged out.
When you try to make a logic comparison you use two assignment operator for compare
in your case you use one assignment operator = so it will return true in first case all the time
so all you need to fix it to add == instead of =
public function index(Request $request)
{
$test = Auth::check();
if ($test == false){
return redirect('/login');
} else {
$providers = $request->user()->providers()->get();
return view ('my-health-hub', compact('providers'));
}
}
We can remove else block completely. It can be written as below (some code optimizations).
public function index(Request $request)
{
$test = Auth::check();
if ($test){
$providers = $request->user()->providers()->get();
return view ('my-health-hub', compact('providers'));
}
return redirect('/login');
}

Laravel save new record returns nothing

I'm trying to save new record, all i get is a white page
even dump and dd for $applicant ->save() returns nothing.
public function store(Request $request) {
try {
if (Auth::guest()) {
return redirect()->route('login');
}
$applicant = new Applicant();
$applicant->first_name = $request->get('first_name');
$applicant->middle_name = $request->get('middle_name');
$applicant->last_name = $request->get('last_name');
dump($applicant);
$applicant->save();
dd('Saved');
} catch (Exception $e) {
Log::error("Error during orders creation:" .$e>getTraceAsString());
}
}
I expected the record should be saved
Try this instead
public function store(Request $request){
$applicant = new Applicant;
$applicant->first_name = $request->input('first_name');
$applicant->save();
}
and don't forget to include use App\Applicant model in your Controller class; If it does not solve your problem. please double check your form action post in view section.
I think save function will not return anything.
for data you must use create method.
Used return after save.
$applicant->save();
return response()->json(['success' => 'Data Added successfully.']);
Use create in stead, write less code if you can us always better.
Try this:
Application::create($request->all());
Or change it the way you need by assigning every array key to its value

How to check if user email is null?

I'm trying to authenticate 2 users by inheritance in a Laravel project.
In my migration I have only 1 column that can be null, that column is email.
With that column I'm expecting to double authenticate professors and alumns, I have also 2 types of registers, one has the input email and the other not.
In my database I have 2 users, one is professor, and the other alumn, professor has email, and the other has email also, because they belong to the same table but that email is NULL in alumn row.
I'm trying to check when I login if that user with email column is null, my view returns alumn.
If it's not null my view returns professor.
I tried to check if email is null in my Laravel controller.
This is my code
public function index()
{
$user = User::where('email', '=', Input::get('email'))->first();
if ($user == 'NULL'){
return ('alumn');
}
if ($user != 'null'){
return ('professor');
}
}
And my Laravel router looks like this.
Route::get('/home', 'HomeController#index')->name('home');
I also tried this function in my controller instead the other one.
if (User::where('email', '=', Input::get('email'))->count() > 0) {
// user found
}
And with exists() instead of count().
If you are wondering, I'm returning just a string right now for testing purposes.
The issue you are having is within your conditionals. ($user == 'NULL') and ($user != 'null'). What you are checking for currently if the User object is the follow string: "NULL".
These are not how you check for null. There are many options that will work.
if (empty($user)){
return view('alumn');
}
// OR
if (!$user) {
return view('alumn');
}
// OR
if (is_null($user)) {
return view('alumn');
}
Would work. You could also use is_null. If you wanted to check that user equals null you cannot put quotation marks around null.
The first() method will return null if there's no data so use is_null() instead like :
if ( is_null($user) ) {
return view('alumn');
}else{
return view('professor');
}
FYI, first() will return you null when there is no data in the database, so I hope this will help you
public function index()
{
$user = User::where('email', '=', Input::get('email'))->first();
if ( is_null($user) ) {
return view('alumn');
} else {
return view('professor');
}
}
All the answers above didn't work in my case.
So i did this to make it worth.
public function index()
{
$user = Auth::user();
if ($user->email == ''){
return ('alumne');
}
else{
return ('professor');
}
print_r(Auth::user());
}
First i printed my Auth::user to check if all was working right, then i tried to save the authentification in a variable called user.
Then i checked with a conditional and all worked fine.
public function index() {
$user = User::where('email', '=', Input::get('email'))->first();
if (empty($user)) {
return view('alumn');
} else {
return view('professor');
}
}

Why redirect show blank page in model laravel?

I'd like to ask why the following code works, redirects normally, and data is successfully inserted :
CategoriesController :
public function store()
{
$data = Input::all();
$category = new Term;
if($category->saveCategory($data)){
return Redirect::route('admin_posts_categories')->withSuccess('Category successfully added.');
}else{
return Redirect::route('admin_posts_categories')->withError('Failed to add category. #ErrorCode : 13');
}
}
Term model :
public function saveCategory($data){
$this->name = $data['name'];
$this->slug = $data['slug'];
if($this->save()){
$category_taxo = new TermTaxonomy;
$category_taxo->term_id = $this->lastCategoryId();
$category_taxo->taxonomy = 'category';
$category_taxo->description = $data['description'];
if($category_taxo->save()){
return true;
}else{
return false;
}
}else{
return "#Error Code : 4";
}
}
Where as the following only inserts the data but then shows a blank page and doesn't redirect :
CategoriesController :
public function store()
{
$data = Input::all();
$category = new Term;
$category->saveCategory($data);
}
Term Model
public function saveCategory($data){
$this->name = $data['name'];
$this->slug = $data['slug'];
if($this->save()){
$category_taxo = new TermTaxonomy;
$category_taxo->term_id = $this->lastCategoryId();
$category_taxo->taxonomy = 'category';
$category_taxo->description = $data['description'];
if($category_taxo->save()){
return redirect::route('admin_posts_categories')->withSuccess('Category successfully added.');
}else{
return redirect::route('admin_posts_categories')->withError('Failed to add category.');
}
}else{
return redirect::route('admin_posts_categories')->withError('#Error Code : 4.');
}
}
Moreover, I'd like to ask a few related questions, does my code conform to correct design patterns, and where should I put the redirect, in the model or in the controller ?
Try this for redirect:
1. return Redirect::back()->withSuccess('Category successfully added.');
OR
2. return Redirect::to(URL::to('admin_posts_categories'))->withSuccess('Category successfully added.');
Add your redirect login inside Controller. Even if you want to put in model (which is not recommended) use Ardent Hook function i.e. afterSave().
First of all never put redirect logic in model. Models are for putting business logic. Second thing check whether you have created route for admin_posts_categories in route.php or not and how you are calling views. If possible post your route code in question.
I recommend not putting redirects in your model. So the first solution would be the best of the two you have.
But back to your problem. It is showing a blank page because your store function is not returning anything. return $category->saveCategory($data); but as previously stated this method is not best practise.
An excellent tip would be to have a look at Laracasts, this will teach you everything you knew, didn't know and more about Laravel.

Resources