Attempt to read property "id" on null - Laravel 8 - laravel

I have problem with this error. I made relationship between :
Meals-Category (hasOne)
Meals-Ingredients (hasMany)
Meals-Tags (hasMany)
Everything is normal with seeding, but when I want to open on endpoint, this messege shows :
"Attempt to read property "id" on null"
Here is my code from Meals Resources, Model and Controller :
Resource:
class Meals extends JsonResource
{
public function toArray($request)
{
return [
'id' => $this->id,
'title' => $this->title,
'description' => $this->description,
'status' => $this->deleted_at > 0 ? 'deleted' : 'created',
'category' => [
'id' => $this->category->id,
'title' => $this->category->title,
'slug' => $this->category->slug,
],
'tags' => TagsResource::collection($this->tags),
'ingredients' => IngredientsResource::collection($this->ingredients),
];
}
}
Model:
class Meals extends Model
{
use SoftDeletes;
use HasFactory;
protected $fillable = ['title', 'description'];
protected $dates = ['deleted_at'];
public function category()
{
return $this->hasOne(Category::class, 'meals_id');
}
public function tags()
{
return $this->hasMany(Tag::class, 'meals_id', 'id');
}
public function ingredients()
{
return $this->hasMany(Ingredient::class, 'meals_id', 'id');
}
}
Controller:
public function index()
{
$meals = Meals::with('category', 'tags', 'ingredients')->get();
return MealsResource::collection($meals);
}

your error means that $this->category is null
assign the category attribute like this :
'category' => $this->load('category')

Related

How can I store forign key a field employee_id without entering it?

I have two tables and the relationship between them is one to many
the model employee is :
class Employee extends Model implements HasMedia
{
use HasFactory;
protected $guarded = [];
protected $casts = [
];
public function familyDetails()
{
return $this->hasMany(FamilyDetails::class,'employee_id');
}
and the model FamilyDetails is:
class FamilyDetails extends Model
{
use HasFactory;
public function employee()
{
return $this->belongsTo(Employee::class,'employee_id');
}
I have an interface asking me to enter information
FamilyDetails table
But within this table there is an employee_id field that joins the two tables together
this is controller:
class FamilyDetailsController extends Controller
{
public function store(StoreFamilyDetailsRequest $request)
{
$familyDetails = FamilyDetails::create($request->validated())->with('employee');
return new FamilyDetailsResource($familyDetails);
}
}
and this is StoreFamilyDetailsRequest :
class StoreFamilyDetailsRequest extends FormRequest
{
public function authorize()
{
return true;
}
public function rules()
{
return [
'Name_kanji' => ['required'],
'Relationship' => ['required'],
'Nama_katakana' => ['required'],
'Grade_In_school' => ['required'],
'Date_of_birth*' => ['required|array'],
'Date_of_birth.*day' => ['required'],
'Date_of_birth.*year' => ['required'],
'Date_of_birth.*month' => ['required'],
];
}
public function validated($key = null, $default = null)
{
return [
'Name_kanji' => $this->Name_kanji,
'Nama_katakana' => $this->Nama_katakana,
'Relationship' => $this->Relationship,
'Grade_In_school' => $this->Grade_In_school,
'Date_of_birth' => Carbon::create(
$this->Date_of_birth['year'],
$this->Date_of_birth['month'],
$this->Date_of_birth['day'])->format('Y-m-d'),
];
}
this is FamilyDetailsResource :
class FamilyDetailsResource extends JsonResource
{
public function toArray($request)
{
return [
'Name_kanji' => $this->Name_kanji,
'Relationship' => $this->Relationship,
'Nama_katakana' => $this->Nama_katakana,
'Grade_In_school' => $this->Grade_In_school,
'Date_of_birth' => [
'month' => $this->Date_of_birth->month,
'day' => $this->Date_of_birth->day,
'year' => $this->Date_of_birth->year,
]
];
}
}
When I run the code in postman the following error appears :
Briefly, how can I store the foreign key field when it is not
It asks me to enter it
in the interface???????
Can you explain more about your relationship table?
I think you can erase your code with in controller store if not used
class FamilyDetailsController extends Controller
{
public function store(StoreFamilyDetailsRequest $request)
{
$familyDetails = FamilyDetails::create($request->validated());
return new FamilyDetailsResource($familyDetails);
}
}

How to make a CRUD for a PackageItem table and get the Item via foreignKey in another table? in Laravel

This is my Item model. I have made a function arrayPackageItemSelect that gets the id and equivalent it to the item name.
class Item extends Model
{
use HasFactory;
protected $fillable = [
'user_id',
'name',
'price',
'itemdescription',
'activeInactive'
];
public function packageitems()
{
return $this->hasMany(PackageItem::class);
}
public static function arrayPackageItemSelect()
{
$arr = [];
$items = Item::all();
foreach($items as $item){
$arr[$item->id] = $item->name;
}
return $arr;
}
}
my PackageItem Model
class PackageItem extends Model
{
protected $fillable = [
'user_id',
'item_id',
'price'
];
protected $table='packageitems';
public static function itemModel()
{
return $this->belongsTo(Item::class);
}
}
my PackageItem Controller (CREATE) and getting the Item ID from another table (Foreign key) so I can put a category for it.
public function addPackageItem(Request $request)
{
$user = Auth::user();
$item = Item::arrayPackageItemSelect();
echo $item; // when I echo this I get Array to Conversion String in POSTMAN
$fields = $request->validate([
'user_id' => 'required',
'item_id' => 'required',
'price' => 'required|numeric'
]);
// // echo $items;
$package = PackageItem::create([
'user_id' => $user->id,
'item_id' => $item,
'price'=> $fields['price']
]);
return response($package, 201);
}
What I get when I echo the Items
The results I get from POSTMAN
My Schema
This is where my reference is https://www.artofcse.com/learning/product-view-insert-update-delete
Can anybody help me what is wrong?
In your controller (addPackageItem method):
$package = PackageItem::create([
'user_id' => $user->id,
'item_id' => $fields['item_id'],
'price'=> $fields['price']
]);
Also, i think there is an error in your PackageItem model. belongsTo should not be called in a static method :
public function itemModel()
{
return $this->belongsTo(Item::class);
}

Unique Rule for two fields failed in Laravel

In my Laravel-5.8, I have this model:
class HrDepartment extends Model
{
public $timestamps = false;
protected $table = 'hr_departments';
protected $fillable = [
'company_id',
'dept_name',
];
public function company()
{
return $this->belongsTo('App\Models\Organization\OrgCompany', 'company_id');
}
}
I tried to use Request Rules
Rules
class StoreDepartmentRequest extends FormRequest
{
public function authorize()
{
return \Gate::allows('department_create');
}
public function rules()
{
return [
'dept_name' => [
'required',
'string',
'min:2',
'max:80',
Rule::unique('hr_departments', 'dept_name', 'company_id')
],
];
}
public function messages()
{
return [
'dept_name.max:80' => 'Department Name cannot be more than 80 characters.',
'dept_name.unique' => 'Department Name already exists.',
'dept_name.required' => 'Please enter the Department Name.',
];
}
}
Controller
public function store(StoreDepartmentRequest $request)
{
$department = HrDepartment::create([
'dept_name' => $request->dept_name,
'company_id' => Auth::user()->company_id,
]);
Session::flash('success', 'Department is created successfully');
return redirect()->route('hr.departments.index');return redirect()->route('hr.departments.index');
}
}
I entered dept_name, Services for company 1, when I entered Services for company 2, I got this error:
'Department Name already exists.',
Why and how do I resolve it?
Thanks
use this code for unique validation
Rule::unique('hr_departments')->ignore($hr_department->id)

Laravel API Resource returned Undefined property: stdClass::$book",

I have a pivot table Book_Category which store the relationship between book table and category table.
In my Book model I have this
public function categories()
{
return $this->belongsToMany(Category::class);
}
In my Category Model` I have this
public function books()
{
return $this->belongsToMany(Book::class);
}
I don't think I need a model for Book_Category since its a pivot table.
But now I need to create an API Resource. I am trying to return a Book of a particular Category
So I do this this
public function singlepage(Request $request,$book)
$relatedCategory = BookCatResource::collection(DB::table('book_category')
->where('category_id', $request->category_id)->get());
I am using query builder because I don't have a model
In my resource, I have this
public function toArray($request)
{
return [
'book_id' => new BookResource($this->book),
'category_id' => $this->category_id
];
}
But it returned error
Undefined property: stdClass::$book",
In your scenario, you do not need to use the model for pivot table,
what you can do is that
Route::get('/', function () {
return CategoryResource::collection(Category::where('id', 1)->get());
});
CategoryResource.php
<?php
namespace App\Http\Resources;
use Illuminate\Http\Resources\Json\JsonResource;
class CategoryResource extends JsonResource
{
public function toArray($request)
{
return [
'id' => $this->id,
'name' => $this->title,
'books' => BookResource::collection($this->books),
'created_at' => $this->created_at,
'updated_at' => $this->updated_at,
];
}
}
BookResource.php
<?php
namespace App\Http\Resources;
use Illuminate\Http\Resources\Json\JsonResource;
class BookResource extends JsonResource
{
public function toArray($request)
{
return [
'id' => $this->id,
'name' => $this->name,
'created_at' => $this->created_at,
'updated_at' => $this->updated_at,
];
}
}

Error storing Topic Model into the database using Sentinel

I have a small forum, im trying to create topic and replies for the store method.
routes.php
Route::get('board/{id}/create', 'TopicsController#create');
Route::post('board/{id}/create', 'TopicsController#store');
TopicsController.php
public function store()
{
$this->request->user()->topics()->create([
'board_id' => $this->request->id,
'title' => $this->request->title,
'body' => $this->request->body
]);
return redirect(url('/board/' . $this->request->id));
}
I am receiving this error.
Call to a member function topics() on null
Also note, i am using Sentinel https://github.com/rydurham/Sentinel from this repo.
<?php namespace App\Models;
class User extends \Sentinel\Models\User
{
protected $fillable = ['email', 'first_name', 'last_name'];
protected $hidden = ['password'];
public function topics()
{
return $this->hasMany(Topic::class);
}
public function replies()
{
return $this->hasMany(Reply::class);
}
public function getGravatarAttribute()
{
$hash = md5(strtolower(trim($this->attributes['email'])));
return "https://www.gravatar.com/avatar/$hash";
}
}
Updated Model
public function store($id)
{
$user = Sentry::getUser($id);
$user->topics()->create([
'board_id' => $this->request->id,
'title' => $this->request->title,
'body' => $this->request->body
]);
return redirect(url('/board/' . $this->request->id));
}
It seems that your user object is null. Properly retrieve the user using the id
public function store($id)
{
$user = \App\Models\User::find(\Sentinel::getUser()->id);
$user->topics()->create([
'board_id' => $this->request->id,
'title' => $this->request->title,
'body' => $this->request->body
]);
return redirect(url('/board/' . $this->request->id));
}

Resources