Laravel policy always return false - laravel

I made a policy for one model.the policy class as following:
namespace App\Policies;
use App\User;
use App\Models\Address;
use Illuminate\Auth\Access\HandlesAuthorization;
class AddressPolicy
{
use HandlesAuthorization;
public function delete(User $user, Address $address)
{
return $user->id === $address->user_id ;
}
}
And I register the policy in authServiceProvider
namespace App\Providers;
use Illuminate\Support\Facades\Gate;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
use App\Models\Address ;
use App\Policies\AddressPolicy;
class AuthServiceProvider extends ServiceProvider
{
/**
* The policy mappings for the application.
*
* #var array
*/
protected $policies = [
'App\Model' => 'App\Policies\ModelPolicy',
Address::class => AddressPolicy::class,
];
/**
* Register any authentication / authorization services.
*
* #return void
*/
public function boot()
{
$this->registerPolicies();
//
}
I use this policy in a controller
namespace App\Http\Controllers\User;
use App\Models\Address;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Auth ;
class AddressController extends Controller
{
public function __construct()
{
$this->middleware('auth');
}
public function destroy(Address $address)
{
$this->authorize('delete', $address);
$address->delete();
return response()->json(['msg'=>'success'], 200);
}
when I request the destroy method in the controller, it always return a 403 status, when I remove this line "$this->authorize ('delete', $address)",the data can be deleted.I've tried several solutions and searched many same problem, none of them resolved my problem.

Related

Laravel problem passing variables from controller to mailer

I am having trouble passing variables from the controller to the mail fucntion I have tried to search it up on google but didn't find anything that works my goal is to get the variable from the form to the welcomemail.blade the current issue is that the variable doesnt get to my wlcomemail.php from the controller. the mailing part itself does work.
Controller code:
$email_data = array(
'first_name'=>'John',
'last_name'=>'Doe',
'email'=>'john#doe.com',
'password'=>'temp',
);
//Customer::create($data);
Mail::to($email_data['email'])->send(new welcomemail($email_data));
welcomemail.php code:
namespace App\Mail;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
class welcomemail extends Mailable
{
use Queueable, SerializesModels;
/**
* Create a new message instance.
*
* #return void
*/
public $email_data;
public $example;
public function __construct()
{
$this->email_data = $email_data;
$this->example = 'example';
}
public function build()
{
return $this->markdown('emails.welcomemail');
}
}
blade code:
# Introduction
Welcome.
{{$email_data['first_name']}}
{{$example}}
#endcomponent
change this:
public function __construct()
{
$this->email_data = $email_data;
$this->example = 'example';
}
to:
public function __construct($email_data)
{
$this->email_data = $email_data;
$this->example = 'example';
}
now you have it in your mail class
it should work

Class App\Http\Requests\TestRequest does not exist? But I am using this class in Controller

I am using same App\Http\Requests\TestRequest in controller but its display message this Class not exit what can be problem? Plz help me?
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests\TestRequest;
use App\Student;
class InsertController extends Controller
{
public function insert(TestRequest $request){
$obj = new Student();
$obj->Name =$request->name;
$obj->City = $request->city;
$obj->save();
return view('submit');
}
}
TestRequest Code is Here!
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class TestRequest 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'
'City'=>'required'
];
}
}
Above Both codes are of Request folder And controller folder, I have done everything, i have done this class in Controller but its showing that not exist why? please Help me.

Laravel giving invalid view error for mail

I'm new to Laravel. I wanted to send a mail to users for every time they login. I wrote the authentication logic already.
<?php
namespace App\Http\Controllers\Users;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use App\Events\Login;
class LoginController extends Controller
{
public function __construct(){
$this->middleware('guest')->except('logout');
}
public function index(){
return view('users.login');
}
public function login(Request $request){
$credentials = $request->only('username', 'password');
if(Auth::attempt($credentials)){
event(new Login(auth()->user()));
return redirect()->intended(route('homepage'));
}else{
return redirect()->back()->withInput()->with('error', 'Username/Password Combo Wrong!');
}
}
public function logout(){
Auth::logout();
return redirect()->route('login-form');
}
}
I wrote an event for this
<?php
namespace App\Events;
use Illuminate\Broadcasting\Channel;
use Illuminate\Queue\SerializesModels;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use App\User;
class Login
{
use Dispatchable, InteractsWithSockets, SerializesModels;
public $user;
/**
* Create a new event instance.
*
* #return void
*/
public function __construct(User $user)
{
$this->user = $user;
}
/**
* Get the channels the event should broadcast on.
*
* #return \Illuminate\Broadcasting\Channel|array
*/
public function broadcastOn()
{
return new PrivateChannel('channel-name');
}
}
This is the event listener
<?php
namespace App\Listeners;
use App\Events\Login;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Request;
use App\Mail\UserLoggedIn;
class SendLoginNotification
{
/**
* Create the event listener.
*
* #return void
*/
public function __construct()
{
//
}
/**
* Handle the event.
*
* #param Login $event
* #return void
*/
public function handle(Login $event)
{
Mail::send($event)->send(new UserLoggedIn($event));
}
}
I created a mail class
<?php
namespace App\Mail;
use App\User;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\Queue\ShouldQueue;
class UserLoggedIn extends Mailable
{
use Queueable, SerializesModels;
public $user;
/**
* Create a new message instance.
*
* #return void
*/
public function __construct(User $user)
{
$this->user = $user;
}
/**
* Build the message.
*
* #return $this
*/
public function build()
{
return $this->from('test#mail.com')->view('emails.users.loggedin');
}
}
I then created the view for the mail in resources/views/emails/users/loggedin.blade.php
<!Doctype html>
<html>
<head>
<title>User Logged In</title>
</head>
<body>
{{$user->name}} Logged in
</body>
</html>
But when i run try to run the login, i get an error saying invalid view
There are a couple of issues I've noticed. Currently, you're:
calling send twice in your SendLoginNotification (and you're passing the Event instead of a mailable to one of them)
not specifying who to send the mail to
also passing the $event to the mailable rather than the User
Change:
Mail::send($event)->send(new UserLoggedIn($event));
To:
Mail::to($event->user)->send(new UserLoggedIn($event->user)); //notice the "user" property.
you didn't pass any variable containing user info.
public function build()
{
$user=User::find(1);
return $this->from('test#mail.com')->view('emails.users.loggedin',compact('user'));
}

Can an Eloquent model has multiple Observer?

Hi I want write a trait to add an observer to model but I thought write boot method is not the right way and finnaly i find that i can boot trait like boot[TraitName] but i wonder if i add an observer with code like this:
trait CreateObserver
{
public static function bootCreateObserver()
{
static::creating(function (Model $model) {
// ...
});
}
}
can I add another observer for my model like below or it will overriding my trait observer?
class MyModel extends Model
{
use CreateObserver;
public static function boot()
{
static::creating(function ($model) {
// ...
});
}
...
}
That's not the right way. I think this might help you:
https://laravel.com/docs/5.6/eloquent#observers
You bind observers to your models using a service boot:
<?php
namespace App\Providers;
use App\User;
use App\Observers\UserObserver;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* #return void
*/
public function boot()
{
User::observe(UserObserver::class);
}
/**
* Register the service provider.
*
* #return void
*/
public function register()
{
//
}
}
Inside the observer you can add all desired functionality:
<?php
namespace App\Observers;
use App\User;
class UserObserver
{
/**
* Listen to the User created event.
*
* #param \App\User $user
* #return void
*/
public function created(User $user)
{
//
}
/**
* Listen to the User deleting event.
*
* #param \App\User $user
* #return void
*/
public function deleting(User $user)
{
//
}
}
And to elaborate. Yes it can have multiple observers. Although I never seen a useful situation for that:
public function boot()
{
User::observe(UserObserver::class);
User::observe(AuthenticableModelsObserver::class);
}
This way both the UserObserver() and AuthenticableModelsObserver() are binded to the User() model on boot.

Singleton created twice

In Laravel 5.4 I have registered a Service Provider that creates a singleton to my Context class which holds application context.
ContextServiceProvider
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use App;
class ContextServiceProvider extends ServiceProvider
{
/**
* Bootstrap the application services.
*
* #return void
*/
public function boot()
{
// Set-up application context
$context = app('context');
}
/**
* Register the application services.
*
* #return void
*/
public function register()
{
$this->app->singleton('context', function ($app) {
return new App\Context();
});
}
}
Then I create a Eloquent model with a global scope.
Model Media
namespace App\Models;
use App\Scopes\SchoolScope;
use Illuminate\Database\Eloquent\Model;
class Media extends Model
{
public static function boot()
{
parent::boot();
static::addGlobalScope(new SchoolScope());
}
}
Now when I access the Context singleton in the scope SchoolScope, the singleton is created twice!
SchoolScope
namespace App\Scopes;
use Illuminate\Database\Eloquent\Scope;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Builder;
use App\Models\School;
class SchoolScope implements Scope
{
protected $school;
public function __construct()
{
$this->school = app('context')->school;
}
public function apply(Builder $builder, Model $model)
{
$builder->where('school_id', '=', $this->school->id);
}
}
Does anyone know why the singleton is created twice?

Resources