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)
Related
I am making a "/bulk" endpoint for my API/REST made in Laravel 8.
My problem is that I don't know how to reuse the same FormRequest that I have for the create or update
json post to: /cars/bulk
{
"cars": [{"model": "A", "year": 2021, "plate": "AA11BB"},{"model": "B", "year": 2021, "plate": "AA12BB"},{"model": "C", "plate": "AA13BB"}]
}
// CarController.php
public function store(CarRequest $request)
{
$car = $this->carService->store($request, Car::class);
}
public function update(CarRequest $request, Car $car)
{
$this->carService->update($request, $car);
}
public function bulk(Request $request)
{
$this->carService->bulk($request);
}
// CarService.php
public function store($request, $modelClass)
{
# My code....
}
public function update($request, $model)
{
# My code....
}
public function bulk($request)
{
foreach ($request->cars AS $carData )
{
$car = Car::where('plate','=',$carData->plate)->first()
# here is the problem,
# howto validate each $car by reusing CarRequest
if ($car){
$this->update($carData, $car);
} else {
$this->store($carData, Car::class);
}
}
}
This is de form request for each item, i have use to for bulk or one request
class CarRequest extends BaseRequest
{
public function authorize()
{
$this->setModel(Car::class);
return $this->isAuthorized();
}
public function rules()
{
$this->setModel(Car::class);
$rules = parent::rules();
$rules = [
'model' => 'required',
'year' => 'required|numeric',
'plate' => 'required'
];
return $rules;
}
public function messages()
{
# multiples messages
}
}
I need reuse my request
Edit: add form request
So I wouldn't suggest using it within a loop how you have in your example, what would be better would be to create a second, bulk request that valiates an array like this.
public function rules()
{
$this->setModel(Car::class);
$rules = parent::rules();
$rules = [
'cars' => ['required', 'array'],
'cars.*.model' => 'required',
'cars.*.year' => 'required|numeric',
'cars.*.plate' => 'required'
];
return $rules;
}
You can do it with same CarRequest form request class as follows.
public function rules()
{
return[
'cars.*.model' => 'required',
'cars.*.year' => 'required',
'cars.*.plate' => 'required',
];
}
Laravel will expect that you are sending nested array. If you dont want to mix it up with CarRequest you can do it with creating another FormRequest class.
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);
}
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));
}