I am building a Laravel website where people can post tasks into a database. Currently, when I post tasks via my form, every account can see the data. How can I show data for only the specific person who posted it?
My blade file
My task controller file
Thank you very much in advance.
If your user has logged in the you can retrieve their id by Auth::user()->id;
In your index() method remove $tasks = Task::all(); and add
$userId = Auth::user()->id;
$tasks = Task::where('user_id',$userId)->get();
Hope this will help
Related
I am currently setting up a new project using Laravel 8. Out of the box, Laravel is configured to use auto-incrementing ID's for the user's ID. In the past I have overrode this by doing the following.
Updating the ID column in the user table creation migration to
$table->uuid('id');
$table->primary('id');
Adding the following trait
trait UsesUUID
{
protected static function bootUsesUUID()
{
static::creating(function ($model) {
$model->{$model->getKeyName()} = (string) Str::orderedUuid();
});
}
}
Adding the following to the user model file
use UsesUUID;
public $incrementing = false;
protected $primaryKey = 'id';
protected $keyType = 'uuid';
On this new project, I did the same as above. This seems to break the login functionality. When the email and password are entered and submitted, the form clears as though the page has been refreshed. Thing to note is there are no typical validation error messages returned as would be expected if the email and/or password is wrong.
To check that the right account is actually being found and the password is being checked properly, I added the following code to the FortifyServiceProvider boot method. The log file confirms that the user is found and the user object dump is correct too.
Fortify::authenticateUsing(function(Request $request) {
\Log::debug('running login flow...');
$user = User::where('email', $request->email)->first();
if ($user && Hash::check($request->password, $user->password)) {
\Log::debug('user found');
\Log::debug($user);
return $user;
}
\Log::debug('user not found');
return false;
});
Undoing the above changes to the user model fixes the login problem. However, it introduces a new problem that is the login will be successful but it wont be the right account that is logged in. For example, there are 3 accounts, I enter the credentials for the second or third account, but no matter what, the system will always login using the first account.
Anyone have any suggestions or ideas as to what I may be doing wrong, or if anyone has come across the same/similar issue and how you went about resolving it?
Thanks.
After digging around some more, I have found the solution.
Laravel 8 now stores sessions inside the sessions table in the database. The sessions table has got a user_id column that is a foreign key to the id column in the users table.
Looking at the migration file for the sessions table, I found that I had forgot to change the following the problem.
From
$table->foreignId('user_id')->nullable()->index();
To
$table->foreignUuid('user_id')->nullable()->index();
This is because Laravel 8 by default uses auto incrementing ID for user ID. Since I had modified the ID column to the users table to UUID, I had forgotten to update the reference in the sessions table too.
I'm a newbee in Cakephp and I have to build a project-management interface for the company where I work in internship. My boss gave me the tables and I have to make the associations.
I have 3 main tables :
MyUsers = a User can have a role between this 3 : Associate, Collaborater, Client
Role = Associate, Collaborater, Client
Client = a "subpart" of the MyUsers table for save informations of Clients.
When I create MyUser and attritute the Client role I would like to register a new Entity in the Client Table. At the moment I tried this in the add function of MyUsersController:
public function add()
{
$myUser = $this->MyUsers->newEntity();
if ($this->request->is('post')) {
$myUser = $this->MyUsers->patchEntity($myUser, $this->request->getData());
if ($this->MyUsers->save($myUser)) {
$clientsTable = TableRegistry::get('Clients');
$client = $clientsTable->newEntity();
// association id user au client
$client->user_id = $myUser->id;
if ($clientsTable->save($client)) {
debug('Yeah !');
}
$this->Flash->success(__('The my user has been saved.'));
return $this->redirect(['action' => 'index']);
}
$this->Flash->error(__('The my user could not be saved. Please, try again.'));
}
$roles = $this->MyUsers->Roles->find('list', ['limit' => 200]);
$this->set(compact('myUser', 'roles'));
}
Obviously it doesn't work because the role 'Client' is assigned at the time of creating the user. With this function all my Users are register in the Clients Table without role distinction.
Do you have any idea how to do to have only Users with Client role?
This is the first time I'm posting here so please tell me if you need any other part of code :)
I hope my English is not too bad :/
Thank's :)
I have trouble getting the problem right I think. But to recap it: You simply want to create "clients" record for an user IF the role is client? So you have a "User has one Client" association.
Assuming this is right, you want to read the Saving Data chapter of the documentation. You must have setup the associations before. If you don't know how to do that read the Associations chapter.
From where does the client data come from? And the role? Based on assumptions:
$myUser = $this->MyUsers->patchEntity($myUser, $this->request->getData());
if ($myUser->role !== Roles::CLIENT) {
$myUser->unsetProperty('client');
}
$this->MyUsers->save($myUser);
Client data is expected to be in $myUsers->client if the form (pure assumption) is containing the data. If not you can just add it there so the ORM realizes it should create a new client record.
I don't think you have understood the basics of the framework and recommend you to do the tutorials first. They'll teach you the required knowledge to deal with the basics of the ORM.
i use the php framework cakePHP to create a web app. There,i want the user to insert in a field as many email addresses as he desires and by hitting the Send button,a message would be emailed to all of the emails.
To achieve that,i have to use bcc.
My problem is that i do not know how can i "read" from the user his email addresses in the right form so that i use them in bcc.
Till now,i have a variable $to = $this->request->data['Mail']['to']; ,where 'Mail' is my model name,and in case the user inserts just one email address,the recipient receives the mail correctly. But how can i enable it to receive multiple email addresses (maybe in an array??) so that i use the variable $to at this piece of code:
$Email = new CakeEmail();
$Email->from($from)
->**bcc($to)**
->subject($subject)
->send($message);
and help is welcomed :)
thank you in advance!
There is the API ( http://api.cakephp.org/2.3/class-CakeEmail.html#_addBcc ) and the code is open source. They all provide the information you are looking for.
If you open the class CakeEmail you will find ( https://github.com/cakephp/cakephp/blob/master/lib/Cake/Network/Email/CakeEmail.php#L482 ):
public function addBcc()
which is different from bcc() since it can be used multiple times to add multiple bcc addresses.
i have a simple question. if i use play.db.ebean.Model to have my Model extend from Model, how can i save it into DB? more clearly: in Django, the database file is created and i save the object, it will be saved into db file and i dont do any sql statements for retrieving or saving objects.. how does this work in playframework?
lets say i have configured my database file in application.conf file like this:
db.default.driver=org.h2.Driver
db.default.url="jdbc:h2:tcp://localhost/~/microblogdb"
db.default.user="sa"
db.default.password=""
now i have a database file somewhere in system.
now i have a Class User which extends Model as i stated above. now i want to save one User object into db. so i will do like this:
User user = new User();
user.username = "testusername";
user.fullname = "userfullname";
user.save();
what will happen after that save() call? can i now directly see my User object in database file?
appreciate any help!
many thanks
Yes it will, if you didn't do any mistakes.
Make sure that in application.conf you also UNcommented the line:
ebean.default="models.*"
Check sample applications in sample folder of the Play package you downloaded. For an example ComputerDatabase (not JPA version) to see the basics of working with Ebean.
What's more you can create constructor(s) in your model to simplify creating User model:
public User(String username, String fullname) {
this.username = username;
this.fullname = fullname;
}
And use it in controller as:
User user = new User("doniyor", "Doniyor The Great");
user.save();
Let's say I have User model and Post model. Post model contains field user_id.
User has $hasMany on Post and Post has $belongsTo on User.
I have some post edit action:
PostsController::edit($id) {
if($this->request->isPost())
{
$this->Post->id = $id;
$this->Post->save();
}
$post = $this->Post->read($id);
$this->set(compact('post'));
}
I use AuthComponent to login users.
How can I prevent user from editing some1 else post? Is there any cake build in function/option to do this? Because some1 can login and post edit action with any id. It's not even case of saving the post data - let's say post is private (only owner should see it) - when someone will call posts/edit/some_id it will see the edit form of this post...
The easier way is to just add this at the beginning of edit action:
$this->Post->id = $id;
if($this->Post->readField('user_id') != $this->Auth->user('id'))
{ //trigger error or redirect }
But I would have to add this at the beginning of each action that updates/reads any data that belongs to some user. So I am looking for more elegant way to do this.
Well an exact example ( handily using a Post/User model too ) is available in the cake manual
Everyones a winner!
Well there is no way of avoiding adding a line to check if a user is authorized to perform an action. Even if you use ACL (Access Control Lists), which is one of Cake's most powerful features.
But as you speak of elegance in general, ACLs will be beauty at its best :) Careful though, they've got a steep learning curve. Don't give up easy, its well worth it.
You should see ACLs from the Book http://book.cakephp.org/1.3/view/1543/Simple-Acl-controlled-Application