laravel Notification Undefined index: user_id - laravel

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.

Related

laravel notifications not storing into my database plus error

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;
}

Policy in Laravel 5.6

I'm trying to have access level control through policy in my Laravel 5.6 application.
I have a Subscriber model and a Company model, Subscribers are only given access to Company by there office locations according to states/region, i.e. a subscriber can view the details of the office if it belongs to the region being assigned to them. for this I have models:
Subscriber
class Subscriber extends Model {
//Fillables and basic attributes being assigned
public function stateIncludeRelation()
{
return $this->belongsToMany('Models\State','subscriber_states',
'subscriber_id', 'state_id');
}
public function user()
{
return $this->belongsTo('Models\User', 'user_id', 'id');
}
}
Company
class Company extends Model {
//Fillables and basic attributes being assigned
public function offices()
{
return $this->hasMany('Models\Company\Office', 'company_id');
}
}
then for Office
class Office extends Model {
//Fillables and basic attributes being assigned
public function company()
{
return $this->belongsTo('Models\Company', 'company_id', 'id');
}}
}
And a common State table:
class State extends Model {
//Fillables and basic attributes being assigned
public function subscriberAccess()
{
return $this->belongsToMany('Models\Subscriber',
'subscriber_states_included_relation',
'state_id', 'subscriber_id');
}
public function companyOffice()
{
return $this->hasOne('Models\Company\Office', 'state', 'id');
}
}
I created a CompanyPolicy something like this:
class CompanyPolicy
{
use HandlesAuthorization;
/**
* Determine whether the user can view the subscriber.
*
* #param User $user
* #param Company $company
* #return mixed
*/
public function view(User $user, Company $company)
{
//Finding subscriber/user state
$userState = State::whereHas('subscriberAccess', function ($q) use($user) {
$q->whereHas('user', function ($q) use($user) {
$q->where('email', $user->email);
});
})->get()->pluck('name');
//Finding company state
$companyState = State::whereHas('companyOffice', function ($q) use($company) {
$q->whereHas('company', function ($q) use($company) {
$q->where('slug', $company->slug);
});
})->get()->pluck('name');
if($userState->intersect($companyState)->all())
return true;
else
return false;
}
}
And registered this to AuthServiceProvider
protected $policies = [
'App\Model' => 'App\Policies\ModelPolicy',
'Models\User' => 'Policies\CompanyPolicy',
];
While trying to fetch something like this in my controller:
public function companyGeneral(Request $request)
{
$user = Auth::user();
$company = Company::where('slug', $request->slug)
->with('offices')
->get()->first();
if($user->can('view', $company))
return response()->json(['data' => $company], 200);
else
return response()->json(['data' => 'Unauthorised'], 403);
}
Everytime I am getting Unauthorised response. Guide me into this. Thanks

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');
}

type casting in laravel json response in relationships eager loading

This is my post model.
class Post extends Model
{
use SoftDeletes;
protected $table = 'posts';
protected $fillable = ['title','featuring_image', 'brief', 'body', 'seen_count'];
public function user(){
return $this->belongsTo(User::class);
}
public function comments()
{
return $this->hasMany(Comment::class);
}
public function someComments()
{
return $this->comments()->limit(Constants::COMMENTS_COUNT_LIMIT);
}
public function commentsCount()
{
return $this->comments()
->selectRaw('post_id, count(*) as count')
->groupBy('post_id');
}
public function likes()
{
return $this->hasMany(Like::class);
}
public function isLiked()
{
return $this->likes()->where('user_id', auth()->check() ? auth()->user()->id : 0);
}
public function likesCount()
{
return $this->likes()
->selectRaw('post_id, count(*) as count')
->groupBy('post_id');
}
}
I executed this query on this model.
$post = Post::with(['categories', 'user', 'commentsCount', 'likesCount', 'isLiked'])->find($post->id);
Because of the relation between this table and like and comment table, The output of this query for 'commentsCount', 'likesCount', 'isLiked' is an array. But I need to receive numbers for 'commentsCount' and 'likesCount', and a boolean for 'isliked' as an output, in laravel josn response.
You might find it easier to use the withCount() the comes with Eloquent instead.
Then for is_liked you could use a scope to get the value and the cast it to a boolean:
public function scopeIsLiked($query)
{
if (is_null($query->getQuery()->columns)) {
$query->select([$query->getQuery()->from . '.*']);
}
$relation = Relation::noConstraints(function () {
return $this->likes();
});
$q = $this->likes()->getRelationExistenceCountQuery(
$relation->getRelated()->where('user_id', auth()->check() ? auth()->user()->id : 0)->newQuery(), $query
);
$query->selectSub($q->toBase(), 'is_liked');
}
Please note you will need to add the use statement for Relation to the top of the class:
use Illuminate\Database\Eloquent\Relations\Relation;
You model could then look like:
class Post extends Model
{
use SoftDeletes;
protected $table = 'posts';
protected $fillable = ['title', 'featuring_image', 'brief', 'body', 'seen_count'];
public function user()
{
return $this->belongsTo(User::class);
}
public function comments()
{
return $this->hasMany(Comment::class);
}
public function someComments()
{
return $this->comments()->limit(Constants::COMMENTS_COUNT_LIMIT);
}
public function likes()
{
return $this->hasMany(Like::class);
}
/**
* Scope to add the "is_liked" flag.
*
* #param $query
*/
public function scopeIsLiked($query)
{
if (is_null($query->getQuery()->columns)) {
$query->select([$query->getQuery()->from . '.*']);
}
$relation = Relation::noConstraints(function () {
return $this->likes();
});
$q = $this->likes()->getRelationExistenceCountQuery(
$relation->getRelated()->where('user_id', auth()->check() ? auth()->user()->id : 0)->newQuery(), $query
);
$query->selectSub($q->toBase(), 'is_liked');
}
}
And your query would look something like:
$post = Post::with('categories', 'user')
->withCount('likes', 'comments')
->isLiked()
->find($post->id);
Hope this helps!
You can use Laravel casts:
Inside the each model you can add the following to cast a value, per example:
protected $casts = [
'isLiked' => 'boolean',
];
Rwd's answer gives a nice solution using scopes, but for laravel 5.4+ you could get away with aliasing the withCount() result and then casting it to boolean with a $cast variable on the model or an accessor (with accessor, you can only get snake case is_liked). This way we don't need to write complex scopes.
The model would be
class Post extends Model
{
// rest of model
protected $casts = ['isLiked'=>'boolean'];
public function likes()
{
return $this->hasMany(Like::class);
}
}
Then in your controller
$post = Post::with('categories', 'user')
->withCount(
[
'likes as likesCount', 'comments as commentsCount',
'likes as isLiked' =>function($query){
$query->where('user_id', auth()->check() ? auth()->user()->id : 0);
}
]
)
->find($post->id);
And now you get likesCount (int), commentsCount (int) and isLiked (boolean)

can't attach topic_id in the comment table

I am making a forum where users can create topics and leave a reply just like this forum.
I made a relationship just like below.However, when I save an article the topic_id does not get attached.I think the saveReply method is wrong.
Also,in this case how do you pass comments on the particular post to the view in the show method??
I am a noob,so if my question is vague I am sorry,but any help will be appreciated!!
Route
Route::group(['middleware' => 'web'], function () {
Route::get('forums','ForumsController#index');
Route::get('forums/create','ForumsController#create');
Route::post('forums', 'ForumsController#store');
Route::get('forums/{category_id}/{title}','ForumsController#show');
Route::post('forums/{category_id}/{title}', 'ForumsController#saveReply');
});
forumcontroller
class ForumsController extends Controller
{
public function index()
{
$categories = Category::all();
$topics = Topic::latest()->get();
return view('forums.index',compact('categories','topics'));
}
public function create()
{
$categories = Category::lists('title', 'id');
return view('forums.create', compact('categories'));
}
public function store(Request $request)
{
Auth::user()->topics()->save(new Topic($request->all()));
flash()->success('投稿しました','success');
return redirect('forums');
}
public function show($category_id, $title)
{
Topic::where(compact('category_id','title'))->first();
return view('forums.post', compact('topic'));
}
public function saveReply (Request $request)
{
Auth::user()->comments()->save(new Comment($category_id,$request->all()));
flash()->success('投稿しました','success');
return redirect()->back();
}
}
topic model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class topic extends Model
{
protected $fillable = [
'title',
'body',
'category_id'
];
public function category()
{
return $this->belongsTo('App\category');
}
public function user()
{
return $this->belongsTo('App\User');
}
public function comments()
{
return $this->hasMany('App\Comment');
}
}
user model
<?php
namespace App;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'password',
];
/**
* The attributes excluded from the model's JSON form.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
public function articles()
{
return $this->hasMany('App\Article');
}
public function topics()
{
return $this->hasMany('App\Topic');
}
public function comments()
{
return $this->hasMany('App\Comment');
}
}
comment model
class Comment extends Model
{
protected $fillable = [
'reply',
'user_id',
'topic_id'
];
public function topic()
{
return $this->belongsTo('App\Topic');
}
public function user()
{
return $this->belongsTo('App\User');
}
}
comment table
class CreateCommentsTable extends Migration
{
public function up()
{
Schema::create('comments', function (Blueprint $table) {
$table->increments('id');
$table->text('reply');
$table->integer('user_id')->unsigned();
$table->integer('topic_id')->unsigned();
$table->timestamps();
});
}
public function down()
{
Schema::drop('comments');
}
}
The Request::all returns an array of all inputs so when you are doing:
new Comment($category_id,$request->all())
You'll get something like this:
1['some' => 'thing', 'other'=> 'values']
Which could be the problem so try this instead:
new Comment(array_merge(['category_id' => $category_id ], $request->all())
When on development/local environment, set the debug true so you'll get meaningful error messages so you can findout the exect problem easily.

Resources