Notifications for comments not working in laravel - php

error
enter image description here
I am trying to send notifications of the event when some likes and comment on his post, notifications for comments and likes working
here is my notification class.
i have error in my CommentController if ($event->user_id != $comment->user_id)
class NewCommentEvent extends Notification
{
use Queueable;
protected $comment;
/**
* Create a new notification instance.
*
* #return void
*/
public function __construct($comment)
{
$this->comment = $comment;
}
/**
* Get the notification's delivery channels.
*
* #param mixed $notifiable
* #return array
*/
public function via($notifiable)
{
return ['database'];
}
/**
* Get the array representation of the notification.
*
* #param mixed $notifiable
* #return array
*/
public function toDatabase($notifiable)
{
return [
'comment' => $this->comment,
'event' => Event::find($this->comment->event_id),
'user' => User::find($this->comment->user_id)
];
}
/**
* Get the array representation of the notification.
*
* #param mixed $notifiable
* #return array
*/
public function toArray($notifiable)
{
return [
//
];
}
}
My controller function code for notifications on comments
public function store(CommentRequest $request)
{
$event = Event::findOrFail($request->event_id);
Comment::create([
'comment' => $request->comment,
'user_id' => Auth::id(),
'event_id' => $event->id
]);
if ($event->user_id != $comment->user_id) {
$user = User::find($event->user_id);
$user->notify(new NewCommentEvent($comment));
}
Toastr::success('Comment post with success','', ["positionClass" => "toast-top-center"]);
return redirect()->back();
}
my CommenRequest
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Support\Facades\Auth;
class CommentRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public function authorize()
{
return Auth::check();
}
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
return [
'comment' => 'required|max:2000',
];
}
}

In your controller: the variable $comment is not defined.
From Laravel docs:
The create method returns the saved model instance.
so the solution is:
$comment = Comment::create([
'comment' => $request->comment,
'user_id' => Auth::id(),
'event_id' => $event->id
]);

you have not defined your $comment, you just created a comment. This is throwing the error
$comment = Comment::create([
.
.
]);
This will fix your issue

The error message was clear. $comment is undefined. Replace your controller code with the follow:
public function store(CommentRequest $request)
{
$event = Event::findOrFail($request->event_id);
// defined comment here
$comment = Comment::create([
'comment' => $request->comment,
'user_id' => Auth::id(),
'event_id' => $event->id
]);
if ($event->user_id != $comment->user_id) {
$user = User::find($event->user_id);
$user->notify(new NewCommentEvent($comment));
}
Toastr::success('Comment post with success','', ["positionClass" => "toast-top-center"]);
return redirect()->back();
}

Related

Property [id] does not exist laravel

i am creating A notifcation for user that created a new post on my site and the user will be awarded point after creating a post, so when a user create a post and get a point send notification but im getting this error
👉 Property [id] does not exist on this collection instance.
please how can I resolve this issue kindly assist me
<?php
namespace App\Http\Livewire;
use App\Gamify\Points\PostCreated;
use App\Models\Category;
use App\Models\Post;
use App\Models\Tag;
use App\Models\User;
use App\Notifications\PointAdd;
use Illuminate\Support\Str;
use Livewire\Component;
use Illuminate\Http\Response;
use Livewire\WithFileUploads;
class PostCreate extends Component
{
use WithFileUploads;
public $post;
public $user;
public $body;
public $slug;
public $photo;
public $title;
public $category = 1;
public $points = 10;
public $energy = 1;
public function increment()
{
$this->points++;
}
protected $rules = [
'category' => 'required|integer|exists:categories,id',
'title' => 'required|min:4',
'body' => 'required|min:4',
];
public function createPost()
{
if (auth()->check()) {
$this->validate();
$random = str_pad(mt_rand(1,999999),6,'0',STR_PAD_LEFT);
$post = Post::create([
'user_id' => auth()->user()->id,
'title' => $this->title,
'category_id' => $this->category,
'body' => $this->body,
'post_number' => $random,
'slug' => Str::slug($this->title),
]);
$user = auth()->user();
$points = $user->givePoint(new PostCreated($post));
$user->notify(new PointAdd($points));
$image = $this->photo->storeAs('posts', str::random(30));
$post->image = $image;
$post->save();
session()->flash("message", "Featured image successfully uploaded");
preg_match_all('/(?<=#)(\w+)/mi', $this->body, $matchedTags, PREG_SET_ORDER, 0);
foreach ($matchedTags as $matchedTag) {
if (!$tag = Tag::where('name', $matchedTag[0])->first()) {
$tag = tag::create(['name' => $matchedTag[0]]);
}
$post->tags()->attach($tag->id);
$tag->addEnergy(1);
}
preg_match_all('/(?<=#)(\w+)/mi', $this->body, $matchedMentions, PREG_SET_ORDER, 0);
foreach ($matchedMentions as $matchedMention) {
optional(User::where('username', $matchedMention[0])->first(), function ($user) {
// $user->notify(new MentionsNotify($user));
});
}
// $users = auth()->user();
// $users->increment('points', 10);
session()->flash('success_message', 'Post was added successfully!');
$this->reset();
return redirect()->route('post.index');
}
abort(Response::HTTP_FORBIDDEN);
}
}
My notification components
<?php
namespace App\Notifications;
use App\Models\Post;
use App\Models\User;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Notification;
class PointAdd extends Notification
{
use Queueable;
/**
* Create a new notification instance.
*
* #return void
*/
public function __construct(User $user)
{
$this->user = $user;
}
/**
* Get the notification's delivery channels.
*
* #param mixed $notifiable
* #return array
*/
public function via($notifiable)
{
return ['mail', 'database'];
}
/**
* Get the mail representation of the notification.
*
* #param mixed $notifiable
* #return \Illuminate\Notifications\Messages\MailMessage
*/
public function toMail($notifiable)
{
return (new MailMessage)
->line('The introduction to the notification.')
->action('Notification Action', url('/'))
->line('Thank you for using our application!');
}
/**
* Get the array representation of the notification.
*
* #param mixed $notifiable
* #return array
*/
public function toArray($notifiable)
{
return [
'user_id' => $this->user->id,
'user_name' => $this->user->name,
'user_avatar' => $this->user->avatar,
'user_points' => $this->user->reputation,
'post_id' => $this->user->post->id,
];
}
}
You are passing a $points object to notification which expects a User model. If your givePoint() method (which you didn't share) does not return a User model then that's the problem.
You can add in your notification, under use Queueable; the protected User $user; definition and check if notification throws an error.

Class App\Http|Controllers\ValidateRegistraion does not exist

I have created a form request using php artisan make:request ValidateRegistration. It created a ValidateRegistration.php file under App\Http\Requests\ directory. After this I have made changes in the store() function of my registration controller ie UserController.php, means I have changed it
FROM
public function store(Request $request)
{
// Save the data
User::create(request(['fname','lname','phone','email','password']));
// redirect to home page
return redirect('/registration-success');
}
TO
public function store(ValidateRagistration $request)
{
// Save the data
User::create(request(['fname','lname','phone','email','password']));
// redirect to home page
return redirect('/registration-success');
}
And added use App\Http\Requests\ValidateRagistration; at the top of the UserController.php file. But when I submit the form without filling anything it shows me an error which is Class App\Http\Controllers\ValidateRegistraion does not exist
EDIT
Added UserController.php and ValidateRegistration.php files.
UserController.php
<?php
use App\Http\Requests\ValidateRegistration;
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\User;
class UserController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
//
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
$title = "Registration";
return view('/registration', compact('title'));
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(ValidateRegistration $request)
{
//// validate requested data
//$this->validate(request(), [
// 'fname' => 'required',
// 'lname' => 'required',
// 'phone' => 'required|size:10',
// 'email' => 'required',
// 'password' => 'required'
//]);
// Save the data
User::create(request(['fname','lname','phone','email','password']));
// redirect to home page
return redirect('/registration-success');
}
/**
* Display the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function show($id)
{
//
}
/**
* Show the form for editing the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function edit($id)
{
//
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param int $id
* #return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
//
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function destroy($id)
{
//
}
}
ValidateRegistration.php
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class ValidateRegistration extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public function authorize()
{
return false;
}
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
return [
'fname' => 'required',
'lname' => 'required',
'phone' => 'required|size:10',
'email' => 'required',
'password' => 'required'
];
}
/**
* Get the error messages for the defined validation rules.
*
* #return array
*/
public function messages()
{
return [
'fname.required' => 'Firstname is mandatoy',
'lname.required' => 'Lastname is mandatory',
'phone.required' => 'Phone is mandatory',
'phone.size' => 'Phone must be 10 digit',
'email.required' => 'Email is mandatory',
'password.required' => 'Password is mandatory',
];
}
}
spot the difference in your class names:
ValidateRagistration
ValidateRegistraion
and I'm guessing it should read ValidateRegistration, clear up typos, they will only confuse things later
at the top of UserController.php swap the positions of the namespace and use lines, namespace should always be first
<?php
namespace App\Http\Controllers;
use App\Http\Requests\ValidateRegistration;
use Illuminate\Http\Request;
use App\User;
and ValidateRegistration.php is in your App\Http\Requests directory
in ValidateRegistration.php I modified the authorize() function. It was returning false. Changed it to true. It is working now.
From
public function authorize()
{
return false;
}
To
public function authorize()
{
return true;
}

Laravel Roles without pivot table

I am student and i am new with Laravel and i have this UserController which used to assign multi Roles to User (using pivot table user_role) but i want to assign one role to each user (without pivot table) so i added role_id foreign in table user but i dont know what to change in UserController file.
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\User;
use App\Role;
use DB;
use Hash;
class UserController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index(Request $request)
{
$data = User::orderBy('id','DESC')->paginate(5);
return view('users.index',compact('data'))
->with('i', ($request->input('page', 1) - 1) * 5);
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
$roles = Role::pluck('display_name','id');
return view('users.create',compact('roles'));
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$this->validate($request, [
'name' => 'required',
'email' => 'required|email|unique:users,email',
'password' => 'required|same:confirm-password',
'roles' => 'required'
]);
$input = $request->all();
$input['password'] = Hash::make($input['password']);
$user = User::create($input);
foreach ($request->input('roles') as $key => $value) {
$user->attachRole($value);
}
return redirect()->route('users.index')
->with('success','User created successfully');
}
/**
* Display the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function show($id)
{
$user = User::find($id);
return view('users.show',compact('user'));
}
/**
* Show the form for editing the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function edit($id)
{
$user = User::find($id);
$roles = Role::pluck('display_name','id');
$userRole = $user->roles->pluck('id','id')->toArray();
return view('users.edit',compact('user','roles','userRole'));
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param int $id
* #return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
$this->validate($request, [
'name' => 'required',
'email' => 'required|email|unique:users,email,'.$id,
'password' => 'same:confirm-password',
'roles' => 'required'
]);
$input = $request->all();
if(!empty($input['password'])){
$input['password'] = Hash::make($input['password']);
}else{
$input = array_except($input,array('password'));
}
$user = User::find($id);
$user->update($input);
DB::table('role_user')->where('user_id',$id)->delete();
foreach ($request->input('roles') as $key => $value) {
$user->attachRole($value);
}
return redirect()->route('users.index')
->with('success','User updated successfully');
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function destroy($id)
{
User::find($id)->delete();
return redirect()->route('users.index')
->with('success','User deleted successfully');
}
}
and you can find all the code here:
http://itsolutionstuff.com/post/laravel-52-user-acl-roles-and-permissions-with-middleware-using-entrust-from-scratch-tutorialexample.html
this mean so much to me if you help me and thanks.

Couchbase with Laravel: Data cannot be inserted in the couchbase

I am new to couchbase and laravel. I am developing an entry form. I am using couchbase as database and in the back-end i am using laravel. when ever i try to insert data in the couchbase, although the query run, but it prints the data on the screen, rather than it stores in the database. Please help me in this issue
This is my model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Member extends Model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Member extends Model
{
//
protected $table = '';
protected $primaryKey = 'id';
public $timestamps = false;
public static $couchbase_bucket = 'default';
public static $couchbase_doc = 'doc1';
protected $fillable = [
'id',
'name',
'father_name',
'constituency' ,
'seat_type',
'profession' ,
'deprtment' ,
'cabinet_post',
'party',
'date_of_birth',
'religon' ,
'marital_status',
'gender' ,
'education',
'present_contact',
'permanent_contact'
];
public static function create(array $attributes = array()){
die(print_r($attributes));
$value = [
'id' => intval($attributes['id']),
'name' => $attributes['name'],
'father_name' => $attributes['father_name'],
'constituency' => $attributes['constituency'],
'seat_type' => $attributes['seat_type'],
'profession' => $attributes['profession'],
'deprtment' => $attributes['department'],
'cabinet_post' => $attributes['cabinet_post'],
'party' => $attributes['party'],
'date_of_birth' => $attributes['date_of_birth'],
'religon' => $attributes['religon'],
'marital_status' => $attributes['marital_status'],
'gender' => $attributes['gender'],
'education' => $attributes['education'],
'present_contact' => $attributes['present_contact'],
'permanent_contact' => $attributes['permanent_contact'],
];
$key = 'insert:and:delete';
$result = \DB::connection('couchbase')->table(self::$couchbase_bucket)->key($key)->upsert($value);
return $result;
}
public static function all($columns = array()){
return \DB::connection('couchbase')->table(self::$couchbase_bucket)->get();
// DB::connection('couchbase')
// ->table('testing')->where('whereKey', 'value')->get();
}
public static function one($id){
return \DB::connection('couchbase')->table(self::$couchbase_bucket)->where('id',$id)->get();
}
}
And the controller is
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Member;
class memberController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
//
$memberdata = Member::all();
return view('member.index')->withuserdata($userdata);
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
//
return view('member.create');
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
//
$input = $request->all();
Member::create($input);
//return redirect('member/index');
}
/**
* Display the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function show($id)
{
//
}
/**
* Show the form for editing the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function edit($id)
{
//
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param int $id
* #return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
//
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function destroy($id)
{
//
}
}

Laravel 5.2 belongstoMany in views

I'm trying to make a belongstoMany relationship in Laravel 5.2.39 between people and places but am unable to pass the information into a view in a select box. I just get: "Error Exception: Undefined variable: people". It also is not saving and making the pivot table entries.
I have created the pivot table person_place with 'place_id' and 'person_id' columns which correspond to the 'people' and 'places' table.
App/Person.php (Person Model)
<?php
namespace ss;
use ss\Place;
use Illuminate\Database\Eloquent\Model;
class Person extends Model
{
/**
* Fillable fields
*
* #var array
*/
protected $fillable = [
'name',
'type',
'status',
'notes',
'email',
'phone',
'alt',
'web',
'first',
'last',
'title',
];
public function places()
{
return $this->belongsToMany('Place');
}
}
App/Place.php (Place Model)
<?php
namespace ss;
use ss\Person;
use Illuminate\Database\Eloquent\Model;
class Place extends Model
{
/**
* Fillable fields
*
* #var array
*/
protected $fillable = [
'name',
'type',
'status',
'notes',
'email',
'phone',
'alt',
'web',
'address1',
'address2',
'city',
'state',
'zip',
'country',
];
public function people()
{
return $this->belongsToMany('Person');
}
}
App/Http/Controllers/PlaceController.php (Places Controller)
<?php namespace ss\Http\Controllers;
use ss\Place;
use ss\Person;
use ss\Http\Requests;
use Illuminate\Http\Request;
use View;
use Session;
class PlaceController extends Controller
{
/**
* Display a listing of the resource.
*
* #return Response
*/
public function index()
{
$places = Place::all();
$people = Person::pluck('name','id')->all();
return View::make('places.index', compact('places','people'));
}
/**
* Show the form for creating a new resource.
*
* #return Response
*/
public function create()
{
$people = Person::lists('last', 'id');
return view('places.create', compact('people'));
}
/**
* Store a newly created resource in storage.
*
* #return Response
*/
public function store(Request $request)
{
$this->validate($request, [
'name' => 'required'
]);
$input = $request->all();
Place::create($input);
Session::flash('flash_message', 'Place successfully added!');
return redirect()->action('PlaceController#index');
}
/**
* Display the specified resource.
*
* #param int $id
* #return Response
*/
public function show($id)
{
$place = Place::findOrFail($id);
return view('places.show')->withPlace($place);
}
/**
* Show the form for editing the specified resource.
*
* #param int $id
* #return Response
*/
public function edit($id)
{
$place = Place::findOrFail($id);
$people = Person::pluck('name','id')->all();
return view('places.edit', compact('place','people'));
}
/**
* Update the specified resource in storage.
*
* #param int $id
* #return Response
*/
public function update($id, Request $request)
{
$this->validate($request, [
'name' => 'required'
]);
$input = $request->except('people');
$place = Place::findOrFail($id);
$peopleIDs = $this->place->people($peopleIds);
$place->fill($input)->save();
Session::flash('flash_message', 'Place successfully edited!');
return redirect()->action('PlaceController#index', $place);
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return Response
*/
public function destroy($id)
{
$place = Place::findOrFail($id);
$place->delete();
Session::flash('flash_message', 'Place successfully deleted!');
return redirect()->action('PlaceController#index');
}
}
resources/views/places/edit.blade.index.php (Places View, where I'm trying to build select list -not working)
#section('aside')
{!! Form::select('people', $people, null, ['class' => '', 'multiple']) !!}
<ul class="section table-of-contents">
<li>New Time</li>
<li>New Money</li>
<li> </li>
<li>New Sub-Task</li>
</ul>
#endsection
resources/views/places/create.blade.index.php (Places View with a select list that works but does not make a pivot table when saving)
#section('aside')
{!! Form::select('people', $people, null, ['class' => '', 'multiple']) !!}
#endsection
Have tried various methods of "with" and "attach" and am unable to get a result. Interestingly, even if I specifically place "$person = "foo"; in my edit method it still says it is undefined.
Thank you for your help.
EDIT: Updated Code
In the PlacesController, your edit($id) method does not pass an array of people to the view.
/**
* Show the form for editing the specified resource.
*
* #param int $id
* #return Response
*/
public function edit($id)
{
$place = Place::findOrFail($id);
$people = People::pluck('name','id')->all();
return view('places.edit', compact('place', 'people');
}

Categories