Send email when new record is inserted in database - laravel

I am creating an api for student management system in laravel. I want to send email to the students when faculty enters their record in the database saying that their admission is successful. How can I do that?

Notifications!
In the method where you insert the record, you want to notify some users.
Final result would look like this:
use App\Notifications\StudentAdmitted;
...
public function doSomething(Request $request, Student $student)
{
$student->admitted = true;
$student->notify(new StudentAdmitted);
}
Create the notification
php artisan make:notification StudentAdmitted
Edit it
You want to modify the toMail method
public function toMail($notifiable)
{
return (new MailMessage)
->greeting('Congratulations!')
->line('you have been accepted')
->action('View', url('/url/to/page'))
->line('something here');
}
Moreover, the Student or User model should use the Notifiable trait.
...
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use Notifiable;
....

Related

laravel manually authenticate user

I want to manually login a user in laravel 8. The problem is that authentication succeeds, but the authenticated user is not stored in the session(or the session is not updated). I use the method given in de docs.
My loginController has two methods: 1) showing the login form and 2) performing the login
<?php
namespace App\Http\Controllers;
use App\Http\Requests\LoginRequest;
use App\Models\User;
use Illuminate\Support\Facades\Auth;
class LoginController extends Controller
{
public function login(){
return view('auth/login');
}
public function validateLogin(LoginRequest $request){
if (Auth::attempt(['email'=>$request->email, 'password'=>$request->password])) {
$request->session()->regenerate();
return redirect()->to('/');
}
return back()->withErrors(['credentials' => 'Deze gegevens zijn niet bekend!']);
}
}
The controller redirects indeed to / , so the user is authenticated but after the redirect the autenticated users is unavailable, so somehow it is not stored in the session.
Does anyone know how to solve this?
I removed the id from the User model as I wanted to use the e-mailadress as the primary key. This violated the Authenticable trait so the session was not updated.
The usermodel needed the following function to replace the id with the email:
public function getKeyName(){
return 'email';
}
The same can be accomplished with:
protected $primaryKey = 'email';
public $incrementing = false;

Call to a member function notify() on string

' I am new in Laravel and I am trying to send notification but it shows an error (Call to a member function notify() on string)'
$discussion->user['email']->notify(new newReplyAdded($discussion));
You need to use notify() on a model, not on a string. Like below
$user = User::find(1);
$user->notify(..)
And you have to use Notifiable trait in you model like
use Illuminate\Notifications\Notifiable;
class User extends Model
{
use Notifiable;
..........
}
In your case, you can try this
$discussion->user->notify(new newReplyAdded($discussion));

How to add Softdeletes to Notifications Table laravel

I am using laravel default database notifications, I want to add softdelete to notifications table.
I have created a migration with softdelete which has added deleted_at column to the notifications table. The problem is I have to add 'use SoftDeletes' to notifications model(according to laravel docs) but cannot find the notifications model.
$table->softDeletes();
I tried adding 'use SoftDeletes' to HasDatabaseNotifications trait but it still deletes the row. Is there another way to add softdelete to notifications table. TIA
In your model at top before start class use
use Illuminate\Database\Eloquent\SoftDeletes;
After class
class Notification extends Model
{
use SoftDeletes;
/**
* The attributes that should be mutated to dates.
*
* #var array
*/
protected $dates = ['deleted_at'];
}
This is how I solved it, I hope it will be useful for you and other friends
App\Classes\MyDatabaseNotification.php
namespace App\Classes;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Notifications\DatabaseNotification;
class MyDatabaseNotification extends DatabaseNotification
{
use SoftDeletes;
protected $dates = ['deleted_at'];
}
App\Classes\MyNotifiable.php
namespace App\Classes;
use Illuminate\Notifications\Notifiable;
trait MyNotifiable
{
use Notifiable;
/**
* Get the entity's notifications.
*/
public function notifications()
{
return $this->morphMany(MyDatabaseNotification::class, 'notifiable')
->orderBy('created_at', 'desc');
}
}
App\User.php
namespace App\Models;
use Illuminate\Foundation\Auth\User as Authenticatable;
use App\Classes\MyNotifiable;
...
class User extends Authenticatable
{
use MyNotifiable;
...

Laravel model: instance or relationship?

I'm not a professional programmer, so I don't know that I'm describing this very well.
Eloquent relationships are established in the model, using syntax and functions such as ... - >belongsTo.. etc.
Behind these models, are tables in my database.
In my (laravel) application, I have a logged in user who needs certain information about other users. At the end of the day, they're all just users, persisting in the user's table.
So when I use a relationship to another object, (e.g. car) all is good. When I try use a relationship to another user I get errors like Cannot redeclare class App\Models\User.
I think I'm misunderstanding something here.
I get the feeling maybe I should be 'instantiating' another version of my User (as 'manager') ... But do I really need to? It's more of a lookup than anything else. I'm not sure I would even know how to do that.
Some pointers please?
It sounds like you created two distinct "User" models:
// /app/User.php:
<?php namespace App;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
// ...
public function user() {
return $this->hasOne('App\Models\User');
}
}
// /app/models/User.php:
<?php namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
// ...
public function user() {
return $this->belongsTo('App\User');
}
}
Instead you want to have a single class which belongs to itself:
// /app/User.php:
<?php namespace App;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
// ...
public function parent() {
return $this->belongsTo('App\User');
}
public function children() {
return $this->hasMany('App\User');
}
}
Then in your database make sure that the users table has a user_id property (edit database/migrations/2014_10_12_000000_create_users_table.php):
$table->integer('user_id')->unsigned()->nullable();
$table->foreign('user_id')->references('id')->on('users');
Now you can attach users to one another:
<?php
$manager = new User();
$employeeOne = new User();
$employeeTwo = new User();
$manager->children()->saveMany([
$employeeOne,
$employeeTwo
]);
dd( $employeeTwo->parent->name ); // Manager's name

Zizaco Entrust 'hasRole' not working within Laravel controller

User model:
<?php
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableInterface;
use Zizaco\Entrust\HasRole;
class User extends Eloquent implements UserInterface, RemindableInterface {
use HasRole;
Role Model:
<?php
use Zizaco\Entrust\EntrustRole;
class Role extends EntrustRole
{
}
Permission Model:
<?php
use Zizaco\Entrust\EntrustPermission;
class Permission extends EntrustPermission
{
}
User controller:
public function postSignin(){
if (Auth::attempt(array('email'=>Input::get('email'),
'password'=>Input::get('password')))) {
$id = Auth::user()->id;
$user = User::where('id','=',$id);
$firstname = Auth::user()->firstname;
if ($user->hasRole("User_Not_Approved")) {
return Redirect::intended('/users/dashboard');
}
Error message:
BadMethodCallException
Call to undefined method Illuminate\Database\Query\Builder::hasRole()
The error message is presented when the IF statement is running, whilst the user is logging in. I have followed Entrust's instructions, but I am at a loss as to why it isn't picking up the method.
Any help would be hugely appreciated!
Try changing: $user = User::where('id','=',$id); to $user = User::find($id);
User::where would need ->get to return what you want, and even then it would return a collection; you would want something like User::where(etc)->first(); to ensure you got a single instance of User. In reality though, since you are retrieving by id, that is what ->find($id) is designed for, and what you should do.

Resources