How to send notices to members who have different membership roles? - laravel

Immediately, I want to ask as I asked in the title.
I Have controller like this:
public function store(Request $request)
{
//
$this->validate($request, [
'status'=> 'required|min:1|max:2',
'subject' => 'required|min:10|max:255',
'body' => 'required|min:10|max:100000'
]);
if ($request->status == 1){
$this->validate($request, [
'email' => 'required|email',
]);
$user = User::whereEmail($request->email)->firstOrFail();
$notice = new Notice();
$notice->user_id = $user->id;
$notice->title = $request->subject;
$notice->priority = $request->priority;
$notice->body = $request->body;
$notice->status = 0;
if ($request->hasFile('featured')){
$featured = $request->featured;
$featured_new_name = time().$featured->getClientOriginalName();
$featured->move('uploads/posts', $featured_new_name);
$notice->file = 'uploads/posts/'. $featured_new_name;
}
$notice->save();
session()->flash('message', "Send Message to ".$user->name." Successful!");
Session::flash('type', 'success');
Session::flash('title', 'Message Send Success!');
return redirect()->route('adminMessage.create');
}
else {
$users = User::all();
if ($request->hasFile('featured')){
$featured = $request->featured;
$featured_new_name = time().$featured->getClientOriginalName();
$featured->move('uploads/posts', $featured_new_name);
$attachment = 'uploads/posts/'. $featured_new_name;
}
foreach ($users as $user){
$notice = new Notice();
$notice->user_id = $user->id;
$notice->title = $request->subject;
$notice->priority = $request->priority;
$notice->body = $request->body;
$notice->status = 0;
if ($request->hasFile('featured')){
$notice->file = $attachment;
}
$notice->save();
}
session()->flash('message', "Send Message to all Users Successful!");
Session::flash('type', 'success');
Session::flash('title', 'Message Send Success!');
return redirect()->route('adminMessage.create');
}
}
I Have 2 status in this field:
For Status 1, I send for selected member (Only One)
For Status 2, I send for all User use $user= User::all();
So I need for help with Send Notice with Membership_role
I Have Memberships Tables, for example like this:
=========================
| id | name | count |
-------------------------
| 1 | free | 200 |
| 2 | free | 200 |
| 3 | free | 200 |
| 4 | free | 200 |
How do I send a message to Membership Id: 2,3,4

If it is a property at the User model, you can use querys to find the user or users you want.
/*
I use a switch just in case you have more than 2 notice statuses to handle
the sendTo functions are functions declared in your controller to handle the cases.
*/
switch($notice->status){
/*Query the user by the membership id to send the notice*/
case 1:
$user = User::where('membership_id',$the_membership)->first();
return $this->sendTo($user);
case 2:
/*Get all users*/
$users = User::all();
return $this->sendTo($users);
/*Handle other notice statuses*/
default:
return $this->sendToDefault();
}

Related

How to return redirect with compact variable in laravel

I have code to do a return redirect as follows
public function addWarrent(Request $request)
{
$add_warrent = new WarrentModel();
$add_warrent->id_warrent = $request->input('id_warrent');
$add_warrent->workunit_id = Auth::user()->workunit_id;
$add_warrent->warr_name = $request->input('warr_name');
$add_warrent->warr_position = $request->input('warr_position');
$add_warrent->warr_category = $request->input('warr_category');
$add_warrent->warr_status = "Belum Diproses";
$add_warrent->warr_dt = Carbon::now();
$add_warrent->warr_tm = Carbon::now();
$add_warrent->save();
Excel::import(new WarrentItemImport, request()->file('warrent_item'));
$warrent_entry_id = WarrentItemModel::where('warrent_entry_id', null)
->update([
'warrent_entry_id' => $request->id_warrent,
]);
$add_head_workunit = WorkunitModel::where('id_workunit', Auth::user()->workunit_id)
->update([
'workunit_head_nip' => $request->workunit_head_nip,
'workunit_head_name' => $request->workunit_head_name
]);
$id = $request->input('id_warrent');
return redirect('satker/print_warrent', compact('id'))->with('success','Berhasil Membuat Surat');
}
And then, I got an error message
Argument 2 passed to
Symfony\Component\HttpFoundation\RedirectResponse::__construct() must
be of the type int, array given, called in
D:\XAMPP\htdocs\Warehouses\vendor\laravel\framework\src\Illuminate\Routing\Redirector.php
on line 233
Why did it happen?
Try one of following
return redirect('/satker/print_warrent/' . $id)->with('success', 'Berhasil Membuat Surat.');
or
return redirect()->route('/satker/print_warrent/')
->with(compact('id'))
->with('success','Berhasil Membuat Surat');;
or
return redirect()->route('/satker/print_warrent/')
->with('id', $id)
->with('success','Berhasil Membuat Surat');;

Laravel : how to use pivot table for taggable system

I want create tag for posts
for example I created three new tags but submit a only a row in TaggablesTable
Tags Table:
id | name |
--------------
1 | first|
2 | two |
3 | three|
taggables Table:
tag_id|taggable_id|taggable_type
-------------------------------
3 | 1 |post
public function store(Request $request)
{
$data = $request->all();
$post = Post::create($data);
if ($post && $post instanceof Post) {
$tags = $request->input('tags');
foreach ($tags as $tag){
$newTag =Tag::firstOrCreate(['name'=>$tag]);
$tags= $newTag->id;
}
$post->tags()->sync($tags);
return redirect()->back();
}
}
How can it be done?
You are overwriting tags every time the loop runs. Map seems like an easier approach to your problem.
$data = $request->all();
$post = Post::create($data);
$tags = collect($request->input('tags'))->map(function (string $tag) {
return Tag::firstOrCreate(['name'=>$tag])->id;
})->all();
$post->tags()->sync($tags);
return redirect()->back();

laravel how to revert only last items deleted by soft delete

i have cart table that save all customer orders in there.
+------------------------------------------------------------------------------+
| id | user_id | product | created_at | updated_at | deleted_at |
+------------------------------------------------------------------------------+
when user soft delete we want to soft delete all items in his cards
when user want to revert we want to revert those items that soft deleted in last time
i can implement it.
this is revert function in my code:
public function revertBackDeletedItems(Request $request)
{
$user = apiGetUser();
if ($user == null) {
return apiAbort(401);
}
$purchaseCartCount = $user->cart()->onlyTrashed()->count();
if ($purchaseCartCount == 0) {
return [
'success' => false,
'message' => 'no items in card '
];
}
$purchaseCartDateTimeInLatestDelete = $user->cart()->onlyTrashed()->orderBy('id', 'desc')->first()['deleted_at'];
$purchaseCarts = PurchaseCart::onlyTrashed()->where('user_id', $user->id)->where('deleted_at', $purchaseCartDateTimeInLatestDelete)->get();
foreach ($purchaseCarts as $key => $purchaseCart) {
$purchaseCart->restore($purchaseCart->id);
}
return ['success' => true];
}
this is the function that delete only the last time items that was deleted?
public function deleteLastTrashed(Request $request)
{
$user = apiGetUser();
if ($user == null) {
return apiAbort(401);
}
$purchaseCartCount = $user->cart()->onlyTrashed()->count();
if ($purchaseCartCount == 0) {
return [
'success' => false,
'message' => 'no items in card '
];
}
$purchaseCartDateTimeInLatestDelete = $user->cart()->onlyTrashed()->orderBy('id', 'desc')->first()['deleted_at'];
$purchaseCarts = PurchaseCart::onlyTrashed()->where('user_id', $user->id)->where('deleted_at', $purchaseCartDateTimeInLatestDelete)->get();
foreach ($purchaseCarts as $key => $purchaseCart) {
$purchaseCart->forceDelete($purchaseCart->id);
}
return ['success' => true];
}
how can i get deleted_at in better way?
this is not a clean code?
i need better way to implement this algorithms
You almost got there:
public function deleteLastTrashed(Request $request)
{
$user = apiGetUser();
if ($user == null) {
return apiAbort(401);
}
$purchaseCartCount = $user->cart()->onlyTrashed()->count();
if ($purchaseCartCount == 0) {
return [
'success' => false,
'message' => 'no items in card '
];
}
// here you know that user has at least one soft deleted cart
$userLastCartSoftDeleted = $user->cart()->onlyTrashed()->orderBy('deleted_at', 'desc')->first();
$userLastCartSoftDeleted->forceDelete();
return ['success' => true];
}
Your could try this:
Add new fields in carts table is_deleted and is_recent so whenever user will delete set is_deleted = 1; and is_recent = 1 to that item which you are going to delete and rest of other is_recent = 0;
During revert fetch that items which have is_recent = 1; and save is_deleted = 1

Laravel : API response with pagination parameter

I want to pass pagination parameters through POSTMAN and pass sort,order,limits in my model to get query with paginate.? how can i do this? Currently it return error.
Currently my route :
http://localhost:8000/api/allpost
My PostController function :
public function index(Request $request)
{
try {
$allPost = Post::allUserPost();
if($allPost !="" && count($allPost)>0) {
return [
'status_code' => 200,
'message' => "Post retrieved successfully",
'PostDetails' => $allPost,
];
} else {
return response()->json([
'message' => "Post data not found",
'status_code' => 403,
]);
}
} catch (\Exception $ex) {
return response()->json([
'message' => "Internal server error",
'status_code' => 500,
]);
}
}
And my POST model function :
public static function allUserPost(Request $request){
$sort = $this->parameters->sort();
$order = $this->parameters->order();
$limit = $this->parameters->limit();
$userPost = Post::with(['product','categories','user.userDetails'])->whereStatus("Active")->orderBy($sort, $order)->paginate($limit)->get();
$userPost_array = $userPost->toArray();
foreach ($userPost_array as $key => $value) {
# code...
$attributes_arr = array_column($userPost_array[$key]['categories'], 'attribute_id');
$category_ids = Attribute::whereIn("id",$attributes_arr)->pluck('category_id');
$category_ids = array_unique($category_ids->toArray());
$category_details_with_att = Post::getCategoryWithAttributeData($attributes_arr,$category_ids);
unset($userPost_array[$key]["categories"]);
$userPost_array[$key]["categories"] = $category_details_with_att->toArray();
}
return $userPost_array;
}
Currently it returns error
Type error: Too few arguments to function App\Post::allUserPost(), 0 passed in D:\xampp\htdocs\IDM\app\Api\V1\Controllers\Front\PostController.php on line 30 and exactly 1 expected
So how can i pass parameters in postmen and whats the solution for this error?
First change this line to $allPost = Post::allUserPost();
$allPost = Post::allUserPost($request);
and then change this code
$sort = $this->parameters->sort();
$order = $this->parameters->order();
$limit = $this->parameters->limit();
To
$sort = $request->sort;
$order = $request->order;
$limit = $request->limit;
and then you can pass these paramets in a query string like
http://localhost:8000/api/allpost?sort=somesort&order=asc&limit=10
Also chage this line
$userPost = Post::with(['product','categories','user.userDetails'])->whereStatus("Active")->orderBy($sort, $order)->paginate($limit)->get();
to
$userPost = Post::with(['product','categories','user.userDetails'])->whereStatus("Active")->orderBy($sort, $order)->paginate($limit);
You are missing an argument when calling the allUserPost function inside the try block.
It should be
$allPost = Post::allUserPost($request);
and then you can retrieve the parameters from the $request variable.
Just change this line in your code
$allPost = Post::allUserPost($request);
And then in your function, you have to change your request type. And after that you have to do one more change only use paginate() method not with get() method.
public static function allUserPost(Request $request){
$sort = $request->sort;
$order = $request->order;
$limit = $request->limit;
$userPost = Post::with(['product','categories','user.userDetails'])->whereStatus("Active")->orderBy($sort, $order)->paginate($limit);
$userPost_array = $userPost->toArray();
foreach ($userPost_array as $key => $value) {
$attributes_arr = array_column($userPost_array[$key]['categories'], 'attribute_id');
$category_ids = Attribute::whereIn("id",$attributes_arr)->pluck('category_id');
$category_ids = array_unique($category_ids->toArray());
$category_details_with_att = Post::getCategoryWithAttributeData($attributes_arr,$category_ids);
unset($userPost_array[$key]["categories"]);
$userPost_array[$key]["categories"] = $category_details_with_att->toArray();
}
return $userPost_array;
}
I hope this will help you.

Laravel Eloquent for Social Network

I'm building a social network. I have Users and Posts. for like concept I created a table (Likes):
_______________________
|id | post_id | user_id |
| | | |
I want to show people who like a post below each post.
so I need to save a row for each Like
.
My problem is Eloquent and how to save a Like row
$post = Post::find($request->postId);
$like = new Likes();
$user = $request->user();
$post->likes()->save($like, $user);
return 'done';
this code set user_id (Likes tabel) 0
is there a better way for Like Concept?
in your controller use this method :
public function postLikePost(Request $request)
{
$post_id = $request['postId'];
$is_like = $request['isLike'] === 'true' ? true:false;
$update = false;
$post = Post::find($post_id);
if(!$post){
return null;
}
$user = Auth::user();
$like = $user->likes()->where('post_id',$post_id)->first();
if($like){
$liked = $like->likes;
$update = true;
if($liked == $is_like)
{
$like->delete();
return null;
}
} else
{
$like = new Like();
//die($like);
}
$like->likes = $is_like;
$like->user_id = $user->id;
$like->post_id = $post->id;
if($update){
$like->update();
}
else{
$like->save();
}
return null;
}

Resources