Total, Quantity, Price in Laravel - laravel

I have a table named 'products' with 5 fields (id, title, price, quantity, total).
My goal is to calculate via the form products.create the total, price * quantity.
Database - products
public function up()
{
Schema::create('products', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('title');
$table->integer('quantity');
$table->double('price');
$table->double('total')->nullable();
$table->timestamps();
});
}
Model - product
protected $fillable = ['title', 'quantity', 'price', 'total'];
public function setTotalAttribute()
{
$this->total = $this->quantity * $this->price;
}
public function getTotalAttribute($value)
{
return $value;
}
** Controller - ProductController**
public function index()
{
$products = Product::oldest()->paginate(5);
return view('admin.products.index', compact('products'))
->with('i', (request()->input('page', 1)-1)*5);
}
public function create()
{
$products = Product::all();
return view('admin.products.create', compact('products'));
}
public function store(Request $request)
{
$request->validate([
'title' => 'required',
'quantity' => 'required',
'price' => 'required',
'total' => 'required'
]);
Product::create($request->all());
return redirect()->route('products.index')
->with('success', 'save');
}
My problem is in my view "products.create" I have 3 fields when I encode the 3 fields, nothing happens ???
Products.create
<form class="panel-body" action="{{route('products.store')}}" method="POST" novalidate>
#csrf
<fieldset class="form-group {{ $errors->has('title') ? 'has-error' : '' }}">
<label for="form-group-input-1">Title</label>
<input type="text" name="title" id="title" class="form-control" value="{{ old('title')}}"/>
{!! $errors->first('title', '<span class="help-block">:message</span>') !!}
</fieldset>
<fieldset class="form-group {{ $errors->has('quantity') ? 'has-error' : '' }}">
<label for="form-group-input-1">Quantity</label>
<input type="text" name="quantity" id="quantity" class="form-control" value="{{ old('quantity')}}"/>
{!! $errors->first('quantity', '<span class="help-block">:message</span>') !!}
</fieldset>
<fieldset class="form-group {{ $errors->has('price') ? 'has-error' : '' }}">
<label for="form-group-input-1">Price</label>
<input type="text" name="price" id="price" class="form-control" value="{{ old('price')}}"/>
{!! $errors->first('price', '<span class="help-block">:message</span>') !!}
</fieldset>
Back
<button type="submit" class="btn btn-sm btn-primary">Valider</button>
Thank you for help.

First of all you didn't send any total value...
$request->validate([
'title' => 'required',
'quantity' => 'required',
'price' => 'required',
]);
Just follow Eloquent ORM
$product = New Product();
$product-title = $request->title;
$product-quantity = $request->quantity;
$product-price = $request->price;
$product-total = $request->price * $request* quantity;
$product->save();
//redirect()

The mutator will receive the value that is being set on the attribute, so your mutator method should be like this on you Product model
public function setTotalAttribute()
{
$this->attributes['total'] = $this->quantity * $this->price;
}

Related

Laravel multi select options ajax request

I'm trying to add multiple courses for a user using ajax. When I click on submit button, everything else updated but the courses. I don't know what I did wrong. Please help me...
This is my blade:
<input type="hidden" name="user_id" id="user_id" value="{{$user_details->id}}">
#csrf
<div class="form-group">
<label for="name">Name</label>
<input type="text" class="form-control" id="name" name="name" value="{{$user_details->name}}">
</div>
<div class="form-group">
<label for="email">Email</label>
<input type="text" class="form-control" id="email" name="email" value="{{$user_details->email}}">
</div>
<div class="form-group">
<label for="courses_id">Courses</label>
#php
$all_courses = $user_details->courses_id;
#endphp
<select name="courses_id[]" multiple id="course" class="form-control nice-select wide">
#foreach($courses as $data)
#if($all_courses)
<option #if(in_array($data->id,$all_courses)) selected #endif value="{{$data->id}}">{{$data->title}}</option>
#else
<option value="{{$data->id}}">{{$data->title}}</option>
#endif
#endforeach
</select>
</div>
<button type="submit" class="btn btn-primary mt-4 pr-4 pl-4">{{__('Update User')}}</button>
</form>
<script>
$(document).ready(function() {
if($('.nice-select').length > 0){
$('.nice-select').niceSelect();
}
$(document).on('change','select[name="courses_id[]"]',function (e) {
e.preventDefault();
var selectedId = $(this).val();
$.ajax({
url : "{{route('admin.user.course.by.slug')}}",
type: "POST",
data: {
_token : "{{csrf_token()}}",
id: selectedId
},
success:function (data) {
$('#course').html('');
$.each(data,function (index,value) {
$('#course').append('<option '+selected+' value="'+value.id+'">'+value.title+'</option>');
$('.nice-select').niceSelect('update');
});
}
});
});
} );
</script>
My controller:
namespace App\Http\Controllers;
use App\Courses;
use App\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
class UserController extends Controller
{
public function edit($id)
{
$user_details = User::find($id);
$courses = Courses::where(['status'=> 'publish'])->get();
return view('backend.user.edit-user')->with([ 'user_details' => $user_details, 'courses' => $courses]);
}
public function user_update(Request $request)
{
$this->validate($request, [
'name' => 'required|string|max:191',
'email' => 'required|string|max:191',
'courses_id' => 'nullable',
],[
'name.required' => __('Name is required'),
'email.required' => __('Email is required'),
]);
User::find($request->user_id)->update([
'name' => $request->name,
'email' => $request->email,
'courses_id' => serialize($request->courses_id),
]);
return redirect()->back()->with(['msg' => __('User Profile Updated Successfully..'), 'type' => 'success']);
}
public function course_by_slug(Request $request){
$all_courses = Courses::where(['status' => 'publish'])->get();
return response()->json($all_courses);
}
}
My route:
Route::prefix(user')->middleware(['adminPermissionCheck:Users Manage'])->group(function () {
Route::get('/edit/{id}', 'UserController#edit')->name('admin.user.edit');
Route::post('/update', 'UserController#user_update')->name('admin.user.update');
Route::post('/course-by-slug', 'UserController#course_by_slug')->name('admin.user.course.by.slug');
});

Laravel Livewire: Validation in array of object

I am new in laravel livewire and having a hard time doing a validation array of object.
In the application, there is an item section and the user can add item/s.
Now all the fields in the item section are required. Once the user submitted form, it did not show the error message in the item section
View
#foreach($items as $i => $item)
<tr>
<td>
<!-- <select class="form-select #error('item_selected_service.{{ $i }}') is-invalid #enderror" type="text" id="service-id" placeholder="Enter member" wire:model.defer="member_id" autofocus> -->
<select class="form-select #error('selected_service_id') is-invalid #enderror" type="text" name="selected_service_id" id="service-id" placeholder="Select Services" wire:model.defer="selected_service_id" autofocus>
<option value="">Please Select</option>
#foreach ($fees as $fee)
<option value="{{ $fee->id }}">{{ $fee->code }} - {{ $fee->name }}</option>
#endforeach
</select>
#error('selected_service_id') <div class="invalid-feedback">{{ $message }}</div> #enderror
</td>
</tr>
#endforeach
Controller
public $members;
public $fees;
public $member_id;
public $date_delivered;
public $terms;
public $date_due;
public $items = [];
public function render()
{
return view('livewire.fees.billings.billing-create');
}
public function mount()
{
$this->members = Member::where('company_id', Auth::user()->company_id)->where('status_id',22)->get();
$this->fees = Fee::where('company_id', Auth::user()->company_id)->where('status_id',20)->get();
$items = new \stdClass();
$items->selected_service_id = '';
$items->quantity = 0;
$items->amount = 0;
array_push($this->items, $items);
}
public function store()
{
$this->validate([
'member_id' => 'required',
'date_delivered' => 'required',
'terms' => 'required|numeric',
'date_due' => 'required',
'items.selected_service_id' => 'required',
]);
}
Question: How to display error message in array of object?
add like this
$this->validate([
'member_id' => 'required',
'date_delivered' => 'required',
'terms' => 'required|numeric',
'date_due' => 'required',
'items.selected_service_id' => 'required',
'member_id.required' => 'Member id is required' //Your Error message
]);

Livewire - I only can Add records to the pivot table - Through checkboxes

I am only able to add records to the pivot table. Really strugling on removing an entry from the pivot table
Livewire Component
<?php
namespace App\Http\Livewire;
use App\Models\User;
use App\Models\Company;
use Livewire\Component;
use Livewire\WithPagination;
class UserAssignCompanySection extends Component
{
use WithPagination;
public $sortBy = 'id';
public $sortAsc = false;
public $user;
public $companies;
public $search;
public $confirmingCompanyRemoval = false;
public $userCompanies = [];
protected $rules = [
'user.name' => 'required',
'user.email' => 'required',
'user.title' => 'required',
'user.first_name' => 'required',
'user.last_name' => 'nullable',
'user.mobile' => 'nullable',
'user.phone' => 'nullable',
'user.is_customer' => 'boolean',
'user.is_provider' => 'boolean',
'userCompanies' => 'required|array',
];
// Table Sort
public function sortBy($field)
{
if($field == $this->sortBy){
$this->sortAsc = !$this->sortAsc;
}
$this->sortBy = $field;
}
// public function updatedUserCompanies()
// {
// $var1 = array_diff(Company::pluck('id')->toArray(),$this->userCompanies);
// dd(Company::pluck('id')->toArray(), $this->userCompanies);
// dd($var1);
// $this->user->companies()->sync($this->userCompanies);
// }
public function updatedUserCompanies()
{
//dd($this->userCompanies);
$this->user->companies()->sync($this->userCompanies);
}
public function mount(User $user)
{
$this->user = $user;
$this->companies = Company::all();
$this->userCompanies = $user->companies()->pluck('company_id')->toArray();
//dd($this->userCompanies);
}
public function render()
{
//$this->user->companies()->sync($this->userCompanies);
return view('livewire.user-assign-company-section');
}
}
<div>
<div class="grid grid-cols-1 text-left xl:grid-cols-6">
<div class="col-span-3 p-4">
<p class="text-lg underline">Name</p>
<x-jet-input wire:model.defer="user.name" id="name" type="text" disabled class="block w-full mt-1 bg-gray-100" />
<x-jet-input-error for="user.name" class="mt-2" />
<br>
#json($userCompanies);
{{-- #foreach ($userCompanies as $item)
{{ $item }}
#endforeach --}}
#foreach($companies as $company)
<div class="mt-1">
<input wire:model="userCompanies" type="checkbox" value="{{ $company->id }}">
{{ $company->name }} <br>
</div>
#endforeach
<br>
{{-- <x-jet-button>Back</x-jet-button> --}}
<br>
</div>
</div>
</div>
When i click on the checbox with company_id = 3 a sting gets added to $this->userCompanies livewire property
something like this
[1,2,"3"];
When i uncheck ids such as 1 and 2 (which was retreived through the DB won't get deleted)
I think it tries to delete a string such as "1" from an array based on integers
If property is array then model have to be declared as array (with dot notation). Try some like this:
#foreach($companies as $i => $company)
<div class="mt-1">
<input wire:model="userCompanies.$i" type="checkbox" value="{{$company->id }}">
{{ $company->name }} <br>
</div>
#endforeach

How to loop through a controller based on product_id in Laravel

I have these models in my Laravel-5.8
Product Model:
class Product extends Model
{
protected $fillable = [
'id',
'name',
];
public function invoice(){
return $this->belongsToMany('App\Invoice');
}
}
Invoice Model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Invoice extends Model
{
protected $fillable = [
'id',
'customer_id',
'product_id',
'invoice_date',
'qty',
'price',
];
public function customer(){
return $this->belongsTo('App\Customer');
}
public function product(){
return $this->belongsToMany('App\Product');
}
}
Each invoice has one or more products.
Invoice Controller
public function create()
{
$customers = Customer::all();
$products = Product::all();
return view('invoice.create', compact('customers','products'));
}
public function store(Request $request)
{
$request->validate([
'customer_id' => 'required',
'product_id' => 'required',
'qty' => 'required',
'price' => 'required',
]);
$invoice = new Invoice();
$invoice->customer_id = $request->customer_id;
.....
return redirect('invoice/'.$invoice->id)->with('message','invoice created Successfully');
}
Invoice: create.blade
<form method="POST" action="{{route('invoice.store')}}">
#csrf
<div class="form-group col-md-3">
<label class="control-label">Customer Name</label>
<select name="customer_id" class="form-control">
<option>Select Customer</option>
#foreach($customers as $customer)
<option name="customer_id" value="{{$customer->id}}">{{$customer->name}} </option>
#endforeach
</select> </div>
<div class="form-group col-md-3">
<label class="control-label">Date</label>
<input name="invoice_date" class="form-control datepicker" value="<?php echo date('Y-m-d')?>" type="date" placeholder="Enter date">
</div>
<table class="table table-bordered">
<thead>
<tr>
<th scope="col">Product Name</th>
<th scope="col">Qty</th>
<th scope="col">Price</th>
</tr>
</thead>
<tbody>
<tr>
<td><select name="product_id[]" class="form-control productname" >
<option>Select Product</option>
#foreach($products as $product)
<option name="product_id[]" value="{{$product->id}}">{{$product->name}}</option>
#endforeach
</select></td>
<td><input type="text" name="qty[]" class="form-control qty" ></td>
<td><input type="text" name="price[]" class="form-control price" ></td>
</tr>
</tbody>
</table>
<div >
<button class="btn btn-primary" type="submit">Submit</button>
</div>
</form>
From the diagram below:
Product_id, qty, price are arrays.
I want the controller to iterate and count the number of products, then the rows of product_id, qty and price in the view will be based on count of products. And then everything will be saved in the invoice table.
How do I complete my store controller code to achieve this?
Try this :
$products = $request->get('product_id');
$qte = $request->get('qty');
$price = $request->get('price');
foreach($products as $key=>$product){
$invoice =Invoice::creeate([
'product_id' => $product,
'qte' => $qte[$key],
'price' => $price[$key],
...
]);
}

Got issues with Assigning User to any Shop in Laravel

I have an issue with assign user to any Shop. i created Shop A and Shop B and want to assign user to each shop. Its work fine, when im assign any user to Shop A. however, when i try assign user to Shop B , user alway got in to Shop A not Shop B.
// My User Model
public function shop()
{
return $this->belongsTo(\App\Shop::class, 'user_id');
}
// My Shop Model
public function user()
{
return $this->hasMany(\App\User::class, 'user_id');
}
// My UserController
public function index()
{
$users = User::all();
$shops = Shop::all();
// return view('user', compact('users', 'shops'));
return UserResource::collection($users);
}
public function create(Request $request)
{
$request->validate([
'name' => 'required',
'email' => 'required',
'password' => 'required',
]);
$user = new user();
$user->user_id = auth()->user()->id;
$user->name = $request->name;
$user->email = $request->email;
$user->password = bcrypt($request->password);
$user->save();
return new UserResource($user);
}
// My User.blade.php Code
#extends('layouts.app')
#section('content')
<div class="container" style="width: 50%">
<h2>Create User</h2>
#if ($errors->any())
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
<form action="user" method="POST">
#csrf
<div class="form-group">
<label for="name">Name</label>
<input type="text" name="name" class="form-control">
</div>
<div class="form-group">
<label for="email">Email</label>
<input type="text" name="email" class="form-control" >
</div>
<div class="form-group">
<label for="password">Password</label>
<input type="password" class="form-control" name="password">
</div>
<div class="form-group">
<label for="shop">Shop</label>
<select name="shops" class="form-control">
#foreach($shops as $shop)
<option value="{{ $shop->id }}">
{{ $shop->name }}
</option>
#endforeach
</select>
</div>
<button class="btn btn-primary">Submit</button>
</form>
</div>
#endsection
Am i doing something wrong with Relationship?
You have two distinct relation from the Shop model to the User model.
// Shop Model
public function users()
{
return $this->hasMany(\App\User::class);
}
public function owner()
{
return $this->belongTo(\App\User::class);
}
If in your controller you want to assign the shop to the user created
public function create(Request $request)
{
$request->validate([
'name' => 'required',
'email' => 'required',
'password' => 'required',
]);
$user = new user();
$user->user_id = auth()->user()->id;
$user->shop_id = $request->shops;
$user->name = $request->name;
$user->email = $request->email;
$user->password = bcrypt($request->password);
$user->save();
return new UserResource($user);
}
For the User Model, you need to define the two different relation with Shop Model
public function shop()
{
return $this->belongsTo(\App\Shop::class); //remove the foreign key or change it to 'shop_id'
}
public function ownedShops()
{
return $this->hasMany(\App\Shop::class);
}

Resources