laravel notifications not storing into my database plus error - laravel

i couldn't store the notification into my notification table inside my database,
i was trying to make notification every time there is a new Post how can i make this work.
Error:
Notification:
use Queueable;
public $post;
public function __construct()
{
}
public function via($notifiable)
{
return ['database'];
}
public function toDatabase($notifiable)
{
return [
'title' => $this->post->title,
];
}
public function toArray($notifiable)
{
return [
];
}
}
Post Controller:
public function store(Request $request)
{
$this->validate($request, [
'title'=>'required|max:100',
'body' =>'required',
]);
$title = $request['title'];
$body = $request['body'];
$post = Post::create($request->only('title', 'body'));
Auth::user()->notify(new NotifyPost($post));
return redirect()->route('posts.index')
->with('flash_message', 'Article,
'. $post->title.' created');
}

You need to inject the post within the construct, or else it never gets resolved.
protected $post;
public function __construct(Post $post)
{
$this->post = $post;
}

Related

laravel get most related post by tag

I have a relationship between post and tag in post show page I'm trying to display post related to the post show content but excluding the main show content it's not working and I'm not getting error.
class PostShow extends Component
{
public $post;
public $body;
public $slug;
public $comment;
public function mount(Post $post) {
$this->post = $post;
}
protected $rules = [
'comment' => 'string|required|min:3|max:5000',
];
protected $listeners = [
'commentWasAdded'
];
public function commentWasAdded() {
$this->post->refresh();
}
public function render() {
$post = Post::where('slug', '=', $slug)->first();
$related = Post::whereHas('tags', function ($q) use ($post) {
return $q->whereIn('name', $post->tags->pluck('name'));
})
->where('id', '!=', $post->id) // So you won't fetch same post
->get();
return view('livewire.post-show',[
'related' => $related,
]);
}
}

Problem with "Route" resource in laravel 8

My app was working fine until I wanted to replace my "get" routes with a single "resource" to be able to include a delete function. I remind you that I am a beginner in laravel so it is surely due to the fact that I can not be able to make a "resource" route.
This is my code :
Route::get('/', function(){
return view('front.pages.homepage');
})->name('homepage');
Route::get('/garages', [GarageController::class, 'index'])->name('garage.index');
Route::get('/garages/{garage}', [GarageController::class, 'show'])->name('garage.show');
Route::get('/garages_create', [GarageController::class, 'create'])->name('garage.create');
Route::post('/garages_create', [GarageController::class, 'garage_create'])->name('garage_create');
Route::resource('cars', [CarController::class]);
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Car;
use App\Models\Garage;
class CarController extends Controller
{
public function index()
{
$list = Car::paginate(10);
return view('cars', [
'list' => $list
]);
}
public function store()
{
$garages = Garage::orderBy('name')->get();
return view('carCreate/carCreate', [
'garages' => $garages,
]);
}
public function create(Request $request)
{
{
$request->validate([
'name' => 'required',
'release_year' => 'required',
'garage_id' => 'required', 'exists:garage_id'
]);
$car = new Car();
$car->name = $request->name;
$car->release_year = $request->release_year;
$car->garage_id = $request->garage_id;
$car->save();
return redirect('/cars');
}
}
public function show(Car $car)
{
return view('carShow/carShow', compact('car'));
}
public function edit($id)
{
//
}
public function update(Request $request, $id)
{
//
}
public function destroy($id)
{
//
}
}
And my error is : ErrorException
Array to string conversion

Broadcast channels not being registered in Laravel

I've been stuck with Broadcasting on private channel in authentication part. What I have done is, I made custom authEndpoint in Echo server
"authEndpoint": "/broadcastAuth",
Controller:
public function broadcastAuth(Request $request){
$channel = $this->normalizeChannelName($request->channel_name);
$broadcaster = new CustomBroadcaster();
$channelAuth = $broadcaster->verifyUserCanAccessChannel($request, $channel);
if($channelAuth){
return true;
}
return response()->json([
'message' => 'Not allowed'
], 403);
}
I have made a custom broadcaster class that extends Illuminate\Broadcasting\Broadcasters\Broadcaster
so that I can override verifyUserCanAccessChannel method
My verifyUserCanAccessChannel method:
public function verifyUserCanAccessChannel($request, $channel)
{
Log::info($this->channels);
foreach ($this->channels as $pattern => $callback) {
if (! $this->channelNameMatchesPattern($channel, $pattern)) {
continue;
}
$parameters = $this->extractAuthParameters($pattern, $channel, $callback);
$handler = $this->normalizeChannelHandlerToCallable($callback);
if ($result = $handler($request->user(), ...$parameters)) {
return $this->validAuthenticationResponse($request, $result);
}
}
throw new AccessDeniedHttpException;
}
Here I have logged $this->channels to get the registered channels from routes/channel.php
But the result is empty.
Here is my BroadcastServiceProvider:
public function boot()
{
require base_path('routes/channels.php');
}
Here is my channel.php:
Broadcast::channel('App.User.{id}', function ($user, $id) {
return (int) $user->id === (int) $id;
});
Broadcast::channel('post-comment.{id}', function ($user, $id){
\Illuminate\Support\Facades\Log::info($user);
return true;
});
And I have uncommented both in config/app.php
Illuminate\Broadcasting\BroadcastServiceProvider::class,
App\Providers\BroadcastServiceProvider::class,
What could be the mistake here. Please help me figure this out.
Thank you in advance.

laravel Notification Undefined index: user_id

I going to do massage notification, I already make the notifications steps,
but gives me this error
when I do dd($notifiable); I found all data
Undefined index: user_id OR
Undefined index: name
public function store(Request $request)
{
$chating=new chats();
$chating->chat = $request->input('chat');
$chating->user_id = Auth::id();
$chating->employee_id = $request->input('employeeid');
$chating->save();
$user_id=$request->input('employeeid');
auth()->user()->notify(new SendMassages($user_id));
return redirect()->back();
}
database notifications table coulmn data {"user_id":5,"name":"Ibrahim"}
Model
protected $user_id;
protected $name;
public function __construct($user_id)
{
$this->user_id = $user_id;
}
public function via($notifiable)
{
return ['database'];
}
public function toDatabase($notifiable)
{
return [
'user_id' => $this->user_id,
'user'=>$notifiable
];
}
View:
{{ $notification->data['name'] }}
Model:
class SendMassages extends Notification
{
use Queueable;
public $user;
public $user_id;
public function __construct($user_id)
{
$this->user_id = $user_id;
}
public function via($notifiable)
{
return ['database'];
}
public function toDatabase($notifiable)
{
// dd($notifiable);
return [
'user_id' => $this->user_id,
'user'=>$notifiable
];
}
}
It seems that you have problem with encapsulation in your code. First you have to make the property of your model into public if you want the quick and not-safe way but if you want the OOP way, You must write setters to do that logic for you.
First and not-safe approach :
class YourModel {
public $user_id;
.
.
.
}
The OOP way:
Class {
public function setUserId(int $userId)
{
$this->user_id = $userId;
}
.
.
.
}
if you are willing to get the exact answer please copy your controllerclass and model in here.

BelongsTo relationship returns null when using relation name "user"

When creating a simple one-to-one relationship in Laravel 5.5, $person->user is returning a null value whenever I use the method/relation name user. If I change the name to foo, User, or login the code seems to work fine. This is the second project I've had this same issue on. Can anyone see what I'm doing wrong?
In Person model:
public function user() {
return $this->belongsTo(User::class, 'user_id', 'id');
}
public function foo() {
return $this->belongsTo(User::class, 'user_id', 'id');
}
public function getUser() {
if ($this->user_id) {
return User::find($this->user_id);
} else {
return null;
}
}
In PersonTest:
$user = factory(User::class)->create();
$person = factory(Person::class)->create(['user_id' => $user->id]);
// This works
$this->assertTrue( $person->getUser()->is($user) );
// This works
$this->assertTrue( !is_null($person->foo) );
if ( $person->foo ) {
$this->assertTrue( $person->foo->is($user) );
}
// This fails
$this->assertTrue( !is_null($person->user) );
if ( $person->user ) {
$this->assertTrue( $person->user->is($user) );
}
By request, here is all of the code relating to Person,
Entire App\Models\Person.php:
use App\Models\User;
use App\Models\Asset;
use App\Traits\HasGuid;
use App\Traits\HasNotes;
use App\Traits\HasModifiedBy;
use App\Traits\HasAttachments;
use App\Traits\HasRelationships;
use App\Transformers\PersonTransformer;
use App\Models\Abstracts\HasTypeModelAbstract;
use App\Models\Interfaces\HasTypeModelInterface;
class Person extends HasTypeModelAbstract implements HasTypeModelInterface {
use HasModifiedBy,
HasNotes,
HasAttachments,
HasRelationships;
protected $fillable = [
'person_type_id',
'email',
'fname',
'lname',
'user_id',
'modified_by_user_id',
'audited_at',
'custom_attributes'
];
protected $casts = [
'custom_attributes' => 'json',
'user_id' => 'integer',
'modified_by_user_id' => 'integer',
'person_type_id' => 'integer'
];
protected $dates = [
'audited_at'
];
public static $transformer = PersonTransformer::class;
public function user() {
return $this->belongsTo(User::class, 'user_id', 'id');
}
public function type() {
return $this->belongsTo(PersonType::class, 'person_type_id');
}
public function assets() {
return $this->hasMany(Asset::class, 'person_id');
}
Traits:
trait HasNotes {
protected static function bootHasNotes() {
static::deleting(function ($instance) {
$instance->notes->each(function ($note) {
$note->delete();
});
});
}
public function notes() {
return $this->morphMany(Note::class, 'notable');
}
}
trait HasModifiedBy {
protected static function bootHasModifiedBy() {
static::saving(function ($instance) {
$instance->modified_by_user_id = Auth::id();
});
}
public function modifiedBy() {
return $this->belongsTo(User::class, 'modified_by_user_id');
}
}
trait HasAttachments {
protected static function bootHasAttachments() {
static::deleting(function ($instance) {
$instance->attachments->each(function ($attachment) {
$attachment->delete();
});
});
}
public function attachments() {
return $this->morphMany(Attachment::class, 'attachable');
}
}
trait HasRelationships {
protected static function bootHasRelationships()
{
static::deleting(function ($instance) {
Relation::forObject( $instance )->delete();
});
}
public function related() { ...[long polymorphic relationship here]... }
/App/Models/Abstracts/HasTypeModelAbstract
use Illuminate\Database\Eloquent\Model;
// This thing just appends some custom attributes dynamically in the JSON and array forms. And no, 'user' is not a custom attribute key.
abstract class HasTypeModelAbstract extends Model {
public function newFromBuilder($attributes = array(), $connection = NULL) {
$instance = parent::newFromBuilder($attributes);
$instance->appendCustomAttributes();
return $instance;
}
protected function appendCustomAttributes() {
$this->append( $this->getCustomAttributesFromType() );
}
public function getCustomAttributesFromType() {
if ($this->type) {
return $this->type->custom_attributes ?
array_keys((array) $this->type->custom_attributes) : [];
} else {
return [];
}
}
protected function setCustomAttributesFromType($attributes = array()) {
if ($this->type) {
$custom_attribute_keys = $this->getCustomAttributesFromType();
$custom_attributes = (array) $this->custom_attributes ?: [];
foreach ($custom_attribute_keys as $key) {
$attributes[$key] = array_get($custom_attributes, $key);
}
}
return $attributes;
}
protected function addMutatedAttributesToArray(array $attributes, array $mutatedAttributes) {
$this->appendCustomAttributes($this, $attributes);
$attributes = $this->setCustomAttributesFromType($attributes);
return parent::addMutatedAttributesToArray($attributes, $mutatedAttributes);
}
protected function mutateAttribute($key, $value)
{
$keys = $this->getCustomAttributesFromType();
if ( in_array($key, $keys) ) {
return $this->getCustomAttributeValue( $key, $value );
}
return parent::mutateAttribute($key, $value);
}
protected function getCustomAttributeValue($key, $value) {
$custom_attributes = (array) $this->custom_attributes ?: [];
return array_get($custom_attributes, $key, $value);
}
I have to be honest - quickly looking at the code I don't see anything wrong but it doesn't mean everything is for sure ok.
If I were you, I would try to limit Person model just to:
class Person extends \Illuminate\Database\Eloquent\Model {
protected $fillable = [
'person_type_id',
'email',
'fname',
'lname',
'user_id',
'modified_by_user_id',
'audited_at',
'custom_attributes'
];
protected $casts = [
'custom_attributes' => 'json',
'user_id' => 'integer',
'modified_by_user_id' => 'integer',
'person_type_id' => 'integer'
];
protected $dates = [
'audited_at'
];
public static $transformer = PersonTransformer::class;
public function user() {
return $this->belongsTo(User::class, 'user_id', 'id');
}
public function type() {
return $this->belongsTo(PersonType::class, 'person_type_id');
}
public function assets() {
return $this->hasMany(Asset::class, 'person_id');
}
}
and now I would verify if everything is fine. If it's fine, now you could investigate this further, add one trait and verify, add second trait and verify, finally extend from same class.
There must be bug somewhere but looking at this code it's hard do find anything
user is reserved name in eloquent.
try User instead of user
public function User() {
return $this->belongsTo(User::class, 'user_id', 'id');
}

Resources