How to get Id field in laravel store function using query builder? - laravel

I'm trying to do a create function in laravel crud controller and I need to get the id of categories to store a new subcategory.
In my categories table on mysql db I have the name field and a father id that represent the father category, I'm making a function to create new subcategories but i'm not able to retrieve the father id
My controller:
{
$request->validate([
'name' => 'required|max:100',
//User insert the name of the father category
'category' => 'exists:categories,name'
]);
$category = new Category();
//I try to extract id from table
$father_id = Category::where('name', '=', $request->input('category'))->value('id');
$category->name = $request->input('name');
$category->father_id = $father_id;
$category->save();
// return $father_id;
return redirect()->route('categories.index')->with('success', 'category added successfully');
}
when I try to return 'father_id' variable is empty

I suggest you build your form using either Categories selection with category's id as value.
This will eliminate possibility your user input a random category name.
And at the same time your problem will be solved because you will get category Id directly from user input / submitted data.
Example
<select name="category_id">
<option value="0">No parent category</option>
<option value="1">Category 1</option>
<option value="2">Category 2</option>
....
</select>
And inside your controller
{
$validated = $request->validate([
'name' => 'required|max:100',
'category_id' => 'integer|exists:categories,id'
]);
// optional here you can add extra checker if combination already exists.
// lets create users's new Category
$category = Category::create([
'name' => $validated['name'],
'father_id' => $validated['category_id'],
]);
return redirect()
->route('categories.index')
->with('success', 'New category is added successfully');
}
Note: there might be error using current validation if category_id is 0

Related

Update record using laravel

I have a question,
I have a form (view) and after submit it saves to the db.
one of the records is id.
when I open the form again for that ID and will press submit again
what will happened it will update the record? or try to create a new record and fail since id is primary key?
so it depends on your controllers etc if you have a updateController with the correct code it can be updated but you would also need a edit method as well, If you could share your code it will be easier to say what would happen instead of guessing
public function store(Request $request)
{
$this->validate($request,[
'name' => 'required|unique:categories',
]);
$category = new Category();
$category->name = $request->name;
$category->slug = str_slug($request->name);
$category->save();
Toastr::success('Category Successfully Save','Success');
return redirect()->route('admin.category.index');
}
If you're trying to update record based on it's id then you could do this
public function update($request)
{
$user = User::firstOrNew([
'id' => $request->id
]);
$user->first_name = $request->first_name;
$user->last_name = $request->last_name;
$user->save();
}
It will find a record with that id, if none was found then create a new record with that id. This is just for example but you need to validate every request before update/insert.

How to pass data from controller to view in Laravel

Please help me. I have these 3 tables, and I have problems on how to call the category name based on the restaurant id from Controller to view. Thank you in advance.
Table items
Table categories
Table restorant
This is my Controller
public function index()
{
if (auth()->user()->hasRole('owner')) {
$items = Items::with('category')->get();
$restorant_id = auth()->user()->restorant->id;
$category = Categories::where(['restorant_id' => $restorant_id]);
}
return view('point-of-sale::index', [
'category' => $category,
'items' => $items,
]);
}
If you add get() to the end of your $category = Categories::where(['restorant_id' => $restorant_id]); statement, you'll have an Eloquent collection returned:
$category = Categories::where(['restorant_id' => $restorant_id])->get();
Pass the $category variable to your view as you are currently, consider renaming it to $categories though just to infer that there could be multiple.
Then in your view you can loop over the Category results and access the name property:
#forelse ($category as $cat)
{{ $cat->name }}
#empty
No categories.
#endforelse
Update
If you want to get items by their category_id, you can either do as you have done with $categories:
$items = Items::where(['category_id' => $category_id])->get();
Alternatively, if you have an items relationship on your Categories model you can access them that way:
$category = Categories::with('items')
->where(['restorant_id' => $restorant_id])
->get();
The above will eager load the items related to a category which you can then access in your view, for example:
#forelse ($category as $cat)
{{ $cat->name }}
#foreach ($cat->items as $item)
{{ $item->name }}
#endforeach
#empty
No categories.
#endforelse

How to catch 1 colomn (id) on table in edit form

I have 1 table data . and I have function edit on this table . in this edit form I have select dropdown to show pluck from database .
I have 3 table . this name is aduan, ipsrs , teknisi
struckture aduan table
id
user_id
ipsrs_id
teknisi_id
aduan
etc.....
ipsrs table
id
nama_bagian
etc....
teknisi table
id
ipsrs_id
nama_teknisi
etc...
This is my controller :
public function index(Request $request)
{
$ipsrs = DB::table('ipsrs')->pluck('nama_bagian','id');
$belum_kerjakan = Aduan::with('users')->where('status','Belum Dikerjakan')->get();
$teknisi = Teknisi::where('ipsrs_id' , 1)->pluck('nama_teknisi', 'id');
$dalam_proses = Aduan::with('users')->where('status','Sedang Dikerjakan')->get();
$selesai = Aduan::with('users')->where('status','Selesai')->get();
return view('admin.admin_dashboard',[
'belum_dikerjakan' => $belum_kerjakan,
'dalam_proses' => $dalam_proses,
'selesai' => $selesai,
'ipsrs' => $ipsrs,
'teknisi' => $teknisi,
]);
}
Example this variable $belum_dikerjakan is showing table data and I have fucntion edit on this table ( in modal) .
But this I don't know how to catch data (ipsrs_id) to set where clause in the pluck . I want to change 1 to ipsrs_id form table , but how ?
If I understood the problem then here is the answer
pull only the ids from ipsrs table and pass to Teknisi table whereIn method
$ipsrsIds = DB::table('ipsrs')->pluck('id')->toArray();
$teknisi = Teknisi::whereIn('ipsrs_id' , $ipsrsIds)->pluck('nama_teknisi', 'id');
public function edit($id)
{
$category =Category::findOfFail($id);
return view('admin.category.edit',compact('category'));
}
public function update(Request $request, $id)
{
$this->validate($request,[
'name' => 'required|unique:categories'
]);
$category = Category::find($id);
$category->name = $request->name;
$category->slug = str_slug($request->name);
$category->save();
Toastr::success('Category Successfully Updated','Success');
return redirect()->route('admin.category.index');
}

-Laravel 5.2 insert logged in users foreign key automatically into product table when creating product

i've been working on a CRUD system lately, what i want is that when a logged in user creates a product on my website his name will automatically be inserted as a foreign key into my product table.
this is my Product model i've made for it.
//inkoopprijs = sell price
//verkoop prijs = buy price
//naam = product name
protected $fillable = ['naam', 'inkoopprijs', 'verkoopprijs','users_id','created_at', 'updated_at'];
protected $table = "product";
this is my ProductController store function
public function store(Request $request)
{
$product = Product::create($request->only(['naam', 'inkoopprijs', 'verkoopprijs', 'users_id']));
return redirect(route('product.index'));
}
You can do this with Eloquent events like so:
Product::creating(function ($product) {
$user = auth()->user();
$product->users_id = $user->id;
});
You can access the current logged in user with Auth::user(); or auth()->user();
We can also access the identifier with Auth::id();
Product::create([
'naam' => $request->get('naam'),
'inkoopprijs' => $request->get('inkoopprijs'),
'verkoopprijs' => $request->get('verkoopprijs'),
'users_id' => \Auth::id()
]);
I hope this is what you meant.
You can use users id as hidden field in the form but need to consider the security aspects of using users id in the form. It depends on where you are using. May be you can use this method is the user is already authenticated.
<input type="hidden" name="users_id" value="{{Auth::user()->id}}">

Laravel maatwebsite import and fill a column with a select form

I'm using maatwebsite's Excel import library to import employees into a database table and it works quite well. However, on the View page where I select the Excel file to import, I have a select drop-down that shows data from the related Companies table, so that that specific selected Company is posted to all the currently imported employees' Comp_id foreign key. I have created the hasMany and belongsTo relations in the respective Company and Employee models.
The data sent in the EmployeeController:
public function viewImport()
{
$employees = Employee::all();
return view('viewImport',
['companies' => Company::pluck('CompanyName', 'Comp_id')
])->withEmployees($employees);
}
public function importExcel(Request $request)
{
if($request->hasFile('import_file')){
$path = $request->file('import_file')->getRealPath();
$data = Excel::load($path, function($reader) {})->get();
$company = Company::.....; /*???????????????
if(!empty($data) && $data->count()){
foreach ($data->toArray() as $key => $value) {
if(!empty($value)){
foreach ($value as $v) {
$insert[] = ['name'=> $v['name'],
'surname'=> $v['surname'],
'idno'=> $v['idno'],
'phone'=> $v['phone'],
'salary'=> $v['salary'],
'dob'=> $v['dob'],
'jobdescription'=> $v['jobdescription'],
'initials'=> $v['initials'],
'Comp_id' => .... /* ???????????????
];
I've included the Company model as class in the EmployeeController.
I want to add a field insertion 'Comp_id' => .... with the Comp_id value of the selected drop-down. How do I create the $company variable in the function so that the selected Comp_id can be inserted for every row? Or is there a completely different way?
Thanks in advance.
Nailed it with 'comp_id' => $request->get('Comp_id').
foreach ($data->toArray() as $key => $value) {
if(!empty($value)){
foreach ($value as $v) {
$insert[] = ['name'=> $v['name'],
'surname'=> $v['surname'],
'idno'=> $v['idno'],
'phone'=> $v['phone'],
'salary'=> $v['salary'],
'dob'=> $v['dob'],
'jobdescription'=> $v['jobdescription'],
'initials'=> $v['initials'],
'comp_id' => $request->get('Comp_id'),
];
assuming your view has a form with a select with your Comp_id, you should be able to grab it from your incomming request:
$company->comp_id = $request->get('Comp_id');
just a hint: have a look at laravel's mass assignment feature.

Resources