Laravel 5.3 Send database notifications - laravel

when admin adds a new appointment for a user, database notification should be created for all admins as well as the assigned user. And When viewing the notifications all the admins should see all notifications while users should see only notifications assigned for them.
public function submitAppointmentForm(Request $request){
$validator = Validator::make($request->all(), [
'respond' => 'required',
'user2_status' => 'required',
]);
if ($validator->fails()) {
return response()->json(['error'=>$validator->errors()->all()]);
}
else
{
$user = Auth::user();
$appointment = new Appointments();
$appointment->project_list_id = $request->project_id;
$appointment->respond = $request->respond;
$appointment->user2_status = $request->user2_status;
$appointment->date = $request->appointment_date;
$appointment->assigned_to = $request->assign_to;
$appointment->user2_note = $request->user2_note;
$appointment->assigned_by = $user->user_id;
$appointment->added_by = $user->user_id;
$appointment->save();
$assign_to = User::where('user_id', $request->assign_to)->first();
Notification::send($assign_to, new NewAppointmentNotification($request));
return response()->json(['success'=>'Successfully added']);
}
}
with above code notifications only added for assigned user. not for admins
how to add admins also when sending notifications
Notification::send($assign_to, new NewAppointmentNotification($request));
UPDATE :
Thanks to Dees Oomens i got it working i did a small modification as per my requirement
$assign_to = User::where('user_id', $request->assign_to)->first();
$users = User::whereHas('roles', function($q){
$q->where('name', 'admin');
})->get();
$users->push($assign_to);
Notification::send($users, new NewAppointmentNotification($request));

First you need to get all admins. You're using entrust so I'm not sure how what role name you've used, but my best guess would be:
$users = User::with(['roles' => function($query) {
$query->where('name', 'admin');
}])->where('id', '!=', $user->id)->get();
$users->push($assign_to);
Notification::send($users, new NewAppointmentNotification($request));
Now all users in the $users array will get the notification. And the $users array contains all admins (but not the current authenticated admin) and the user which is $assign_to.

Related

Update record using laravel

I have a question,
I have a form (view) and after submit it saves to the db.
one of the records is id.
when I open the form again for that ID and will press submit again
what will happened it will update the record? or try to create a new record and fail since id is primary key?
so it depends on your controllers etc if you have a updateController with the correct code it can be updated but you would also need a edit method as well, If you could share your code it will be easier to say what would happen instead of guessing
public function store(Request $request)
{
$this->validate($request,[
'name' => 'required|unique:categories',
]);
$category = new Category();
$category->name = $request->name;
$category->slug = str_slug($request->name);
$category->save();
Toastr::success('Category Successfully Save','Success');
return redirect()->route('admin.category.index');
}
If you're trying to update record based on it's id then you could do this
public function update($request)
{
$user = User::firstOrNew([
'id' => $request->id
]);
$user->first_name = $request->first_name;
$user->last_name = $request->last_name;
$user->save();
}
It will find a record with that id, if none was found then create a new record with that id. This is just for example but you need to validate every request before update/insert.

How to manipulate a Laravel collection with related models and return a customized instance?

My model relation
return $this->hasMany('App\Models\Opportunity')->with('user');
My Attempt
$project = Project::find(1);
$$opportunities = $project->opportunities
->where('status', "confirmed");
$opportunities->each(function ($opportunity) {
return $opportunity->get('user');
});
Goal
My goal is to return the data in the following structure:
Opportunities:
Opportunity:
Status,
Amount
Currency
Name
Note that the user is a subset of the opportunity itself.
Problem
This returns a 1024 SQL error.
Ideally
It would be ideal if I can return all this information with the query itself.
Call get() method on your query to get its results first:
$oppurtunities = $project->opportunities()
->where('status', "confirmed")
->get();
You have eager loaded the user instance for each opportunity so just call $opportunity->user to return each opportunity's user:
$project = Project::find(1);
$opportunities = $project
->opportunities()
->where('status', "confirmed")
->get();
$filtered = $opportunities->map(function ($opportunity) {
return [
'status' => $opportunity->status,
'amount' => $opportunity->amount_pledged,
'currency' => $opportunity->currency,
'name' => optional($opportunity->user)->full_name
];
})->all();

Query lastest Relationship, When Account was Created

I have two tables: Account and Transaction.
These tables relate to each other, by Account hasOne Transaction.
i want to show data in Transaction page, once Account was created.
My Account Model
public function transactions()
{
return $this->hasOne(\App\Transaction::class)->latest();
}
My Transaction Model
public function account()
{
return $this->belongsTo(\App\Account::class);
}
And my TransactionController
(I tried to implement code like below, but still no luck):
public function index()
{
$transactions = Transaction::with(['account' => function($query) {
$query->orderBy('id', 'desc')->first();
}]);
return response()->json(['transactions' => $transactions]);
}
Any Help? Thanks.....
QueryBuilder chains need either a get() or a first() or something of that nature at the end to execute the query, right now the variable you're passing to the view is the unexecuted query builder. Try this
$transactions = Transaction::with(['account' => function($query) {
$query->orderBy('id', 'desc')
}])->get();
Although, as TimLewis pointed out in the comments, if the relationship between transactions and accounts is one to one then there's no need to do any ordering of the account so it can just be this
$transactions = Transaction::with('account')->get();
Oooopppp i found what i want....
In my AccountController
public function store(Request $request)
{
$validateData = $request->validate([
'name' => 'required',
'code' => 'required',
]);
$account = new Account();
$account->user_id = auth()->user()->id;
$account->code = $request->code;
$account->name = $request->name;
$account->description = $request->description;
$account->balance = $request->balance;
$account->save();
$transaction = new \App\Transaction();
$transaction->credit = $request->balance;
$account->transaction()->save($transaction);
return response()->json(['created' => true]);
}
i have to save Transaction Relationship with Account.

How to queue the logics in controller

I have used two logic in my controller in my laravel project
public function multiStore()
{
$user = User::create([
'name'=>$request->name,
'email'=>$request->email,
'password'=>Hash::make($request->name),
]);
$post = MyPost::create([
'name'=>$request->post_name,
'body'=>$request->post_body,
]);
return redirect()->to('/admin/home);
}
Is it possible to make like if user is created successfully only then the post will be created so that I can use post created by user relationship
I have tried something like if condition but it is not working
You can try the code bellow , I assume you have a user_id field in posts table since you mentio9ned a relation ship. This is not the best way but i try to keep things simple, so I just edited the code.
Note : make sure you listed all the table fields in protected $fillable in your model before using Create()
public function multiStore()
{
$user = User::create([
'name'=>$request->name,
'email'=>$request->email,
'password'=>Hash::make($request->name),
]);
if($user){
$post = MyPost::create([
'user_id' => $user->id
'name'=>$request->post_name,
'body'=>$request->post_body,
]);
}
return redirect()->to('/admin/home);
}
Enclose your query in database transaction
https://laravel.com/docs/5.8/database#database-transactions
Either you can:
DB::transaction(function() {
Model::create();
AnotherModel::create();
});
Or you can use the following to find and catch error...
DB::beginTransaction();
// Your queries here...
// Model::create();
// AnotherModel::create();
DB::commit();

Query returning every row null in laravel

I'm trying to build a chat application using laravel echo and pusher, everything works but the data that returns to the databse is either null or the default value, here's the code
public function sendMessage(Request $request){
$conID = $request->conID;
$message1 = $request->message;
$user = Auth::user();
$fetch_userTo = DB::table('messages')
->where('conversation_id', $conID)
->where('user_to', '!=', Auth::user()->id)
->get();
$userTo = $fetch_userTo[0]->user_to;
$message = Message::create([
'user_from' => Auth::user()->id,
'user_to' => $userTo,
'conversation_id' => $conID,
'message' => $message1,
]);
if($message) {
$userMsg = DB::table('messages')
->join('users', 'users.id','messages.user_from')
->where('messages.conversation_id', $conID)->get();
broadcast(new MessagePosted($message))->toOthers();
return $userMsg;
}
}
NB: when i put insert() instead of create in the query the data goes through the database normally but there's an error in broadcasting
Have you tried to create a message like this? instead of using a model event?
$message = new Message;
$message->user_from = Auth::user()->id;
$message->$user_to = $userTo;
$message->conversation_id = $conID;
$message->message = $message1;
$message->save();
You have a lot more control this way, i.e
if($message->save()) { ... }
Or you could wrap the whole thing in a transaction?
Be sure your Message model allows the fields that you want to add in the $fillable array
Create method check fillable attributes into Laravel model. You have to write your all columns into fillable and then use create method.
Second solution is use Active Record technique. #Devin Greay answer is helpful to use Active record.
More information visit https://laravel.com/docs/5.6/eloquent#mass-assignment

Resources