I am using Laravel to build a simple Movie management System.
When a User creates a Movie in my DB, I use the following
public function store()
{
$input = Input::except('_token');
$id = Helpers::loggedInUser()->id;
$input['creator_id'] = $id;
$this->title->create($input);
return Redirect::back()->withSuccess( trans('main.created successfully') );
}
This successfully passes the users id and stores in it a creator_id field
I want to restrict users from editing Movies which they did not create. So in the edit function I have
public function edit($title)
{
$title = $this->title->byURi( e($title) );
$id = Helpers::loggedInUser()->id;
$titleuser=$title['creator_id'];
if ( $titleuser = $id )
{
return View::make('Titles.Edit')->withTitle($title)->withType('movies');
}
}
However, this does not seem to work. Anyone with a movie.edit permission in my sentry user db can still see the view.
If you compare two variables you have to use two equal signs, otherwise you set the first variable to the value of the second.
if ( $titleuser == $id )
Related
I have a command that I'll run nightly using the Forge scheduler. The command simply loops through and sends emails to each user who qualifies for one.
COMMAND:
public function handle()
{
//Get all users
$users = User::all();
$data = [];
$renewalEmail = '';
foreach($users as $user)
{
//Check each users next_biling_date and see if is less than 72 hours from now, if so send reminder email
$nextBillingDate = ($user->hasSubscription())? $user->getSubscriptionData()->current_period_end : false;
$now = strtotime(now());
$threeDaysFromNow = 60*60*24*3;
//($user->hasSubscription())? $this->updateNextBillingDate($user) : false;//TODO: remove after working: follow up
if($user->hasSubscription() && $nextBillingDate-$now<=$threeDaysFromNow)
{
$data = [
'name' => $user->name,
'billingdate' => date('n/j/Y',strtotime($user->next_billing_date)),
];
// Log::info(print_r($data,true));
$renewalEmail = Mail::to('my#email.com')->send(new SubscriptionRenewalReminder($data));
// Log::info(print_r($renewalEmail,true));
}
}
return true;
}
My Mailable is pretty straight forward:
public function __construct($data)
{
$this->data = $data;
}
/**
* Build the message.
*
* #return $this
*/
public function build()
{
Log::info('SubscriptionRenewalReminder Email build() called: ');
$firstName = explode(' ',$this->data['name'])[0];
$billingDate = $this->data['billingdate'];
Log::info('firstname: '.$firstName);
Log::info('billingDate: '.$billingDate);
return $this->view('emails.subscription-renewal-reminder')
->from('my#email.com', 'Project')
->subject('Project Subscription Is About To Renew')
->withName($firstName)
->withBillingdate($billingDate);
}
All of my Log::info's dump out the right information. I have 3 test users who all qualify to get the email.
In my testing, all three emails show the first user's name and billing date. Instead of unique emails, they are all identical.
I may move this into a queue but on a small set of users this should work fine. TIA
I have users with role manager, and I only want them to update or view other users(employee) data that belong in the same department as the manager user. If the manager user is not in the same department as the user he's trying to update it should redirect the back.
i.e., the manager might try to change the user id in the URL, and I want to deny access to if that user belongs in another department.
I have all my roles and permissions set up.
The Department field is in USER TABLE
public function show($id)
{
$team = User::where('id', $id)->with('roles')->first();
return view('backend.user.team.show', compact('team'));
}
public function edit($id)
{
$user_roles = Role::all();
$team = User::find($id);
$business = Business::all();
return view('backend.user.team.edit', compact('team', 'user_roles', 'business'))->with('user', auth()->user());
}
You should use policies and gates.
Take a look at the documentation:
Writing policies
Writing gates
Basically, you should do something like this:
Create a policy to handle your user permissions:
php artisan make:policy UsersPolicy
This command will create a UsersPolicy file within the App/policies/ directory.
Open the UsersPolicy file and create a checkUserDepartament within that file:
public function checkUserDepartament(User $user, User $userToBeManaged)
{
return $user->departament === $userToBeManaged->departament;
}
The function above return true if the current logged in user departament is the same of the user you want to edit. Otherwise, return false.
Within your AuthServiceProvide:
Gate::define('user-belongs-to-same-departament', 'App\Policies\UsersPolicy#checkUserDepartament');
To use the Gate, do something like this within your controller:
use Gate; //At the top of the controller.
// I assume that $id is the id of the user you want to edit.
public function edit($id)
{
if(Gate::allows('user-belongs-to-same-departament', User::find($id))){
$user_roles = Role::all();
$team = User::find($id);
$business = Business::all();
return view('backend.user.team.edit', compact('team', 'user_roles', 'business'))->with('user', auth()->user());
}else {
return response('Unauthorized', 401);
}
}
Hope it helps.
Top of my controller i have added:
use Auth;
function in my controller
public function details($id)
{
if(Auth::check())
{
$user = Auth::user();
$product = Product::find($id);
$cart->product_id = $product->id;
$cart->category_id = $product->category_id;
$cart->user_id = $user->id;
dd($cart->user_id); //check if its storing the value
}
else {
return redirect()->route('login');
}
}
when I run this i get error:
Creating default object from empty value
If I remove the $user->id line the error goes.
I tried adding constructor also but still got same error
public function __construct() {
$this->middleware('auth');
}
dd is showing other details after it checks if user is logged in.
Is there a way to get user id of logged in user from users table that is created by default.
Thanks!
The issue is you’re calling $cart->product_id, but the $cart variable isn’t defined as far as I can see. PHP doesn’t know what to do, so because you try and assign a property to it, PHP assumes you want $cart to be a class, hence the “Creating default object from empty value” message.
Other than that, you code could be improved by using middleware to authenticate your users, and relations on your Eloquent models so you’re not manually assigning relation IDs.
Try like this,
You forgot to initials cart object
$cart = new Cart;
$cart->product_id = $product->id;
$cart->category_id = $product->category_id;
$cart->user_id = $user->id;
dd($cart->user_id); //check if its storing the value
On the edit profile page for a user, I want to show the existing values of the current logged-in user details like name, email, gender etc. My questions are as follows
Is it recommendable to user Auth::user()->name , Auth::user()->email directly to populate the form fields ? Or shall I create a variable like $user = Auth::user(); in my controller and pass it on to my view to $user like a regular object?
Does using Auth::user(), multiple times on a given view file hit my database each time I use it?
Thanks in advance.
If you look at the SessionGuard.php file in Illuminate\Auth, you'll see the method user() which is used to retrieve the currently authenticated user:
/**
* Get the currently authenticated user.
*
* #return \Illuminate\Contracts\Auth\Authenticatable|null
*/
public function user()
{
if ($this->loggedOut) {
return;
}
// If we've already retrieved the user for the current request we can just
// return it back immediately. We do not want to fetch the user data on
// every call to this method because that would be tremendously slow.
if (! is_null($this->user)) {
return $this->user;
}
$id = $this->session->get($this->getName());
// First we will try to load the user using the identifier in the session if
// one exists. Otherwise we will check for a "remember me" cookie in this
// request, and if one exists, attempt to retrieve the user using that.
$user = null;
if (! is_null($id)) {
if ($user = $this->provider->retrieveById($id)) {
$this->fireAuthenticatedEvent($user);
}
}
// If the user is null, but we decrypt a "recaller" cookie we can attempt to
// pull the user data on that cookie which serves as a remember cookie on
// the application. Once we have a user we can return it to the caller.
$recaller = $this->getRecaller();
if (is_null($user) && ! is_null($recaller)) {
$user = $this->getUserByRecaller($recaller);
if ($user) {
$this->updateSession($user->getAuthIdentifier());
$this->fireLoginEvent($user, true);
}
}
return $this->user = $user;
}
// If we've already retrieved the user for the current request we can just return it back immediately. We do not want to fetch the user data on every call to this method because that would be tremendously slow.
if (! is_null($this->user)) {
return $this->user;
}
So, calling the user() multiple times won't make multiple calls to the database.
You'll get only 1 request to database, so using Auth::user() multiple times is not a problem.
I recommend you using Laravel Debugbar as the most comfortable way for app optimization.
Using
public function _prepareOptions(Varien_Object $buyRequest, $product, $processMode)
{
$options = parent::_prepareOptions($buyRequest, $product, $processMode);
$options['start_date'] = date here
$options['end_date'] = date here
return $options;
}
in my module I can save some custom options.
I can see them in the "sales_flat_quote_item_option" table.
What i'm stuck on is trying to retrieve and display these values with the order in the admin in this template
"app\design\adminhtml\default\default\template\sales\items\column\name.phtml"
Is there a way to get these options via the $_item variable in the template or will i need to use the orderid and models.
Still not sure which is the correct way but used the buyRequest object
public function prepareForCartAdvanced(Varien_Object $buyRequest, $product = null, $processMode = null)
{
$buyRequest->setData('start_date', $start);
}
Then in the view,
$_item->getBuyRequest()->getData('start_date');