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));
}
Related
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);
}
}
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')
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);
}
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)
I am fetching products along with its relationship. I have done this:
$data = $this->products->with('images')->with('colors')->where('slug', $slug)->first();
And in the Product model, I have written:
public function images(){
return $this->hasMany('App\Models\ProductImages', 'product_id');
}
public function colors(){
return $this->hasMany('App\Models\ProductSizes', 'color_id');
}
I am storing color_id in the product_sizes table so now when I do dd($data). It gives me 5 data inside the object where the size_id are different but the color_id are same. Is it possible to group the data coming in colors relationship?
I tried using array_unique in the blade but that did not gave me to use the following function:
public function colorInfo(){
return $this->belongsTo('App\Models\Color', 'color_id');
}
I want to group the color_id coming in the colors relationship to display available colors of the product.
Code as per request:
Product Model
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Product extends Model
{
protected $fillable = ['name','slug','sku','category_id','brand_id','video','status', 'specification', 'description','warranty', 'vendor_id'];
public function getRules(){
$rules = [
'name' => 'bail|required|string|unique:products,name',
'slug' => 'bail|required|string|unique:products,slug',
'sku' => 'bail|required|string|unique:products,sku',
'specification' => 'bail|required|string',
'description' => 'bail|required|string',
'category_id' => 'required|exists:product_categories,id',
'brand_id' => 'nullable|exists:brands,id',
'vendor_id' => 'nullable|exists:vendors,id',
'video' => 'nullable|string',
'warranty' => 'nullable|string',
'status' => 'nullable|in:active,inactive',
];
if($rules != 'add'){
$rules['name'] = "required|string";
$rules['slug'] = "required|string";
$rules['sku'] = "required|string";
}
return $rules;
}
public function category(){
return $this->belongsTo('App\Models\ProductCategory');
}
public function brand(){
return $this->belongsTo('App\Models\Brand');
}
public function VendorName(){
return $this->belongsTo('App\Models\Vendor', 'vendor_id');
}
public function images(){
return $this->hasMany('App\Models\ProductImages', 'product_id');
}
public function sizes(){
return $this->hasMany('App\Models\ProductSize', 'product_id');
}
public function colors(){
return $this->hasMany('App\Models\ProductSize', 'product_id');
}
public function finalCategory(){
return $this->belongsTo('App\Models\SecondaryCategory', 'category_id');
}
}
PRoduct Sizes Model
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class ProductSize extends Model
{
protected $fillable = ['product_id','size_id', 'selling_price', 'purchase_price', 'discount','stock', 'color_id', 'quantity','total_price'];
public function getRules(){
$rules = [
'product_id' => 'required|exists:products,id',
'size_id' => 'required|exists:sizes,id',
'color_id' => 'required|exists:colors,id',
'selling_price' => 'required|string',
'purchase_price' => 'required|string',
'quantity' => 'required|string',
'total_price' => 'required|string',
'discount' => 'nullable|string',
'stock' => 'required|string',
];
return $rules;
}
public function colorInfo(){
return $this->belongsTo('App\Models\Color', 'color_id');
}
}
Get the product first.
$data = $this->products->with(['images', 'colors'])->where('slug', $slug)->first();
To get the distinct colors for that product.
$unique_product_colors = $data->colors->unique('color_id');
unique('color_id') method can be applied on a collection instance to get a new collection in which all the items will have unique color_id
Try This
$data = $this->products->with('images')->with('colors')->where('slug', $slug)->groupBy('product_sizes.color_id')->first();