Laravel - Policy multiple values - BelongsToMany - laravel

I have three tables: users, files and file_project.
Each file has an user_id.
The administrator can delete every file, but the user only the files he uploaded.
view.blade.php
file table
file_project table
After i submit the form i get these:
[
"23",
"22",
"24"
]
So, now I can delete the files from Controller.
This is the Controller:
public function deleteSelected (Request $request)
{
$files = $request->files;
File::destroy($files);
return redirect()->back();
}
How can i use Policies and check for multiple ids?
I can now identify the records from file table, using the ids from $files
public function deleteSelected (Request $request)
{
$files = $request->files;
return $list = File::find($files);
}
And the response is:
Any help?
Thanks!

If you want to allow only users with permissions to delete the file you can use the following:
public function deleteSelected (Request $request)
{
$files = $request->files;
$loggedInUser = Auth::user();
if(!$loggedInUser->isAdmin() || File::whereIn('id', $files)->where('user_id', $loggedInUser->id)->count() < count($files)) {
abort(403);
}
File::destroy($files);
return redirect()->back();
}
And then add the logic for isAdmin in your User Model

Related

Restrict some users to update or view other users data in Laravel

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.

Gathering data from multi page form, and adding additional data

So I'm data from a multi-page form, the data is stored like this.
I'm using this tutorial https://www.5balloons.info/multi-page-step-form-in-laravel-with-validation/
public function store(Request $request)
{
$user = $request->session()->get('user');
$user->save();
return redirect('/home');
}
That works fine. But how do I add additional data manually using the arrow function? For example, I need to set a status, the ip address, ect. Something like 'status' => 1
Assuming this is the only place you want to add these values to users, you could just add the values after you got it from the session:
public function store(Request $request)
{
$user = $request->session()->get('user');
$user->ip_address = '127.0.0.1';
$user->status = 1;
$user->save();
return redirect('/home');
}
you can add addition data like:
if your $user is laravel object then
$user->setAttribute('status', '1');
or $user if array then
$user['status']=1;

How to correctly store data based on Id in Laravel Eloquent

I have a table called Diaries in my DB which is linked to my Users table. A user can have many Diaries but a diary can only belong to one user.
I want to save data to a row in my Diaries table based on user id. When a users logs in, he can fill a form which calls the save method to save to the row in Diaries corresponding to that user.
I'm using Laravel's Auth.
public function save(Request $request)
{
$id = Auth::id();
$error = $request->error;
$fix= $request->fix;
$diary = new Diary();
$diary->error = $error;
$diary->fix=$fix;
$result = $diary->id->save;
if($result==true)
{
echo "saved";
}else{
echo "not saved";
}
public function save(Request $request)
{
$result = $request->user()->diaries()->create([
'error' => $request->error,
'fix' => $request->fix,
]);
// you should have "diaries" relation in User model and setup fillables for Diary
if($result==true)
{
echo "saved";
}else{
echo "not saved";
}

Rename file in Laravel 5.3

I want to rename existing files in Laravel .. like I have items table and every item has picture .. and when I rename the item I mean update the item ..
I want to rename the image as well ..
This is my code ..
public function update(Request $request, $id)
{
$color = Color::find($id);
$old_value = $color->color_name;
if($request->ajax())
{
$check = Color::where('color_name','=',$request->color_name)->count();
if($check == 1 and $request->color_name <> $old_value)
{
return response()->json([
'error'=>'same',
'old_value'=>$old_value,
]);
}
else
{
$color->color_name = $request->color_name;
$color->save();
$file = base_path()."/public/upload/colors/1/$old_value.jpg";
/* here where i want to rename the variabel file to the new name com from the request */
}
}
}
Check out the Official Documentation for your needs
Storage::move('old/file1.jpg', 'new/file1.jpg');
I think you might be able to change the file name when you use move method
Filesystem/Cloud Storage

Laravel - Best way to store user and his/her dynamically created relations on submit

Which way should I store User Relations which are made "Dynamically"?
By that i mean. I have People table with record of husband for example now husband can add as relation to him (hasMany) his wife and children. Now I have setup the model and it works
Model
This relations are in same table as data is same for them I only need to know if they belong to husband
public function children(){
return $this->hasMany( get_class($this) ,'people_id','id');
}
public function parent(){
return $this->belongsTo( get_class($this) , 'people_id','id');
}
Now when i go to form and add a person husband there. I would have an option to dynamically add his children() (his wife, his children, his grandma...) and submit once its done.
Now i have tought about saving these children to Session first (put them in array) and on submit to post it to controller. Is this a good way or should i do it some other way?
(I hope i explained this well, if not i will try to explain it better)
I have done it like this i dont know if this way is ok but it works for me. Also to add i have just used name for the DB data as i wanted to get this to work.
Store parent and his/her children (if any) in DB from Session
public function store(AdminCreatePersonRequest $request)
{
$data = $request->all();
$parent = new Person;
$parent->name = $data['name'];
$parent->save();
$children = $request->session()->pull('children');
if ($children != null) {
foreach($children as $childData){
$child = new Person(['name' => $childData['child-name']]);
$parent->children()->save($child);
}
}
return redirect('dashboard')->with('success', ['The user was successfully created']);
}
AJAX
Add child to session
public function add(AdminCreatePersonChildRequest $request)
{
$temp = $request->session()->get('children',[]);
$data = $request->all();
unset($data['_token']);
array_push($temp,$data);
end($temp);
$key = key($temp);
$data += ['id' => $key];
$request->session()->put('children', $temp);
return $data;
}
Remove child from session
public function delete(Request $request, $id) {
$temp = $request->session()->pull('children');
unset($temp[$id]);
$request->session()->put('children', $temp);
return 1;
}
Load children from Session on view create (if any)
public function load(Request $request) //get children from session (if exists)
{
$data = $request->session()->get('children');
if($data != null){
return $data;
}
else {
return 0;
}
}
Clear all children from session
public function clear(Request $request) //remove children from session
{
$request->session()->forget('children');
return 1;
}
And with data form controller you update your view (in my case add <li> to <ul> element)

Resources