I am trying to update the database record but Laravel update() function is not working. I have fillable array in the model. but still, it is not working.
The Property Model:
class Property extends Model
{
use HasFactory;
protected $table = 'properties';
protected $primaryKey = 'proID';
public $timestamps = false;
protected $fillable = [ 'proID', 'ProStatus', 'ProPurpose', 'ProType', 'SubType', 'basePrice', 'unitPrice', 'Width', 'Length', 'LandArea','PropertyNumber', 'water', 'electricity', 'gas', 'severage', 'fk_Street', 'createdBy', 'delete'];
public function streets(){
return $this->belongsTo(Street::class,'fk_Street');
}
public function hasInstallments(){
return $this->hasMany(Installments::class,'proID');
}
The PropertyController:
public function destroy($id)
{
$property = Property::find($id);
$property->delete = true;
if($property->save()){
return response()->json(['success'=>true]);
}
}
the $property->update() always returns true but record does not update in database.
The method update() is for mass update wich require an array of attributes and bypass mutators.
public function destroy($id)
{
$property = Property::find($id);
$property->update(['delete' => 1]);
}
You might want to use save() instead
public function destroy($id)
{
$property = Property::find($id);
$property->delete = 1;
$property->save();
}
Both will update the record, you'll need to implement your method's return logic on top of this code but as for updating the record, I think you get the idea.
Your property table primary key is "proID"
public function destroy($id)
{
$property = Property::where('proID', $id)->first();
if($property->update(['delete' => 1])) {
return response()->json(['success' => true]);
}
}
I have defined an attribute in my model and want to use it in a scope.
protected $appends = ['lowest_price'];
public function getLowestPriceAttribute()
{
$lowest_price = NULL;
foreach($this->shops as $shop) {
if(is_null($lowest_price)) {
$lowest_price = (double)$shop->pivot->price;
}
if($lowest_price > (double)$shop->pivot->price) {
$lowest_price = (double)$shop->pivot->price;
}
}
return $lowest_price;
}
The lowest_price attribute I would like to use in a scope but it's always 'null':
public function scopeMaxPrice(Builder $query, $max_price): Builder {
return $query->where('max_price', '>=', $this->lowest_price);
}
If I dd(); the getLowestPriceAttribute function in the scope it also returns 'null'. In my view I have access to the 'lowest_price' attribute.
Can the attribute be part of the query? If not, is there an elegant solution?
EDIT: The scope gets called in the Product controller:
public function index()
{
$products = QueryBuilder::for(Product::class)
->allowedFilters(
AllowedFilter::exact('type_id')->default('1'),
AllowedFilter::scope('min_speed')->default(0),
AllowedFilter::scope('min_range')-> default(0)
# AllowedFilter::scope('max_price')-> default(999)
)
->get();
$types = DB::table('types')->pluck('name', 'id');
return view('pages.home', compact('products', 'types'));
}
Note: I am using the Spatie querybuilder
Hello I am making a cart but when I click on add to cart link then it says: "Too few arguments to function App\Http\Controllers\admin\ProductController::addToCart(), 2 passed and exactly 3 expected", how can i sole this error error https://ibb.co/C2FZYD9
Thanks in advance,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,
model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Cart
{
private $contents;
private $totalQty;
private $contentsPrice;
public function __construct($oldCart){
if ($oldCart) {
$this->contents = $oldCart->contents;
$this->totalQty = $oldCart->totalQty;
$this->totalPrice = $oldCart->totalPrice;
}
}
public function addProduct($product, $qty){
$products = ['qty' => 0, 'price' => $product->price, 'product' => $product];
if ($this->contents) {
if (array_key_exists($product->slug, $this->contents)) {
$product = $this->contents[$product->slug];
}
}
$products['qty'] +=$qty;
$products['price'] +=$product->price * $product['qty'];
$this->contents[$product->slug] = $product;
$this->totalQty+=$qty;
$this->totalPrice += $product->price;
}
public function getContents()
{
return $this->contents;
}
public function getTotalQty()
{
return $this->totalQty;
}
public function getTotalPrice()
{
return $this->totalPrice;
}
}
routes:
Route::get('cart', 'Admin\ProductController#cart')->name('product.cart');
Route::get('/addToCart/{product}', 'Admin\ProductController#addToCart')->name('addToCart');
controller:
public function cart()
{
if (!Session::has('cart')) {
return view('products.cart');
}
$cart = Session::has('cart');
return view('product.cart', compact('cart'));
}
public function addToCart(Product $product, Request $request, $qty)
{
if(empty(Auth::user()->email)){
$data['email'] = '';
}else{
$data['email'] = Auth::user()->email;
}
$oldCart = Session::has('cart') ? Session::get('cart') : null;
$qty = $request->qty ? $request->qty : 1;
$cart = new Cart($oldCart);
$cart->addProduct($product, $qty);
Session::put('cart', $cart);
return redirect()->back()->with('flash_message_success', 'Product $product->title has been successfully added to Cart');
}
This is your route:
Route::get('/addToCart/{product}', 'Admin\ProductController#addToCart')->name('addToCart');
and your function definition:
public function addToCart(Product $product, Request $request, $qty)
{
// ...
}
This function expects the $product and $qty to be passed through your route.
Too few arguments to function App\Http\Controllers\admin\ProductController::addToCart(), 2 passed and exactly 3 expected
This error means you only pass the product to the route.
Change the function definition or pass the parameter to the route and it will work.
Update
This is a small example, defining an option parameter to your addToCart function:
public function addToCart(Product $product, Request $request, $qty=0)
{
// ...
}
and for your route:
Route::get('/addToCart/{product}/{qty?}', 'Admin\ProductController#addToCart')->name('addToCart');
Hope it helps.
In your addToCart there are only two parameters passed so it searches for the third parameter in function addToCart. At mine this worked.
Route::get('/addToCart/{product}/{qty?}', 'Admin\ProductController#addToCart')->name('addToCart');
Here my screenshot :
I want the CRUD operation like that above mentioned image.Can anyone help me with the sample code for this?
Your Controller
//add new member
public function function_name()
{
//add all input fields here with key (example)
$params = array(
'emp_name' => $this->input->post('name'),
);
$add = $this->your-model-name->function_name($params);
}
//For delete member
public function function_name($id) //$id is the ID to delete member
{
$delete = $this->your-model-name->function_name($id);
}
//Update member
public function function_name($id) //$id is the ID to update member
{
//all input fields of member you want to update (i.e. name)
$params = array(
'emp_name' => $this->input->post('name'),
);
$update= $this->your-model-name->function_name($id);
}
Your Model
public function function_name($params) //For add member
{
return $this->db->insert('table-name', $params);
}
public function function_name($id) //For delete member
{
$this->db->where('column-name', $id);
return $this->db->delete('table-name');
}
public function function_name($id) //For update member
{
$this->db->where('column-name', $id);
$this->db->set('column-name', $value);
return $this->db->update('table-name');
}
I have the following data model
A technician can have many services and a service can have many technical
Tecnico Model
class Tecnico extends Eloquent{
protected $table = 'Tecnico';
protected $fillable = array('Auth_Token');
public function servicios(){
return $this->belongsToMany('Servicio', 'Servicio_Tecnico', 'idTecnico', 'idServicio');
}
}
Servicio Model
class Servicio extends Eloquent{
protected $table = 'Servicio';
public function detalleServicio(){
return $this->hasOne('Detalle_Servicio', 'idDetalle_Servicio');
}
public function tecnicos(){
return $this->belongsToMany('Tecnico', 'Servicio_Tecnico', 'idServicio', 'idTecnico');
}
}
I'm trying to get all the services of a particular technician according to the "auth_token"
ServicioController
class ServicioController extends BaseController{
public function obtenerServicios($auth){
if($auth != ''){
$tecnico = DB::table('Tecnico')->where('Auth_Token',$auth)->first();
if($tecnico != null){
$servicio = $tecnico->servicios;
$response = Response::json($tecnico);
return $response;
}else{
$array = array('Error' => 'NotAuthorizedError', 'Code' => '403');
$response = Response::json($array);
return $response;
}
}else{
$array = array('Error' => 'InvalidArgumentError', 'Code' => '403');
$response = Response::json($array);
return $response;
}
}
}
Route
Route::get('servicio/{auth}', array('uses' => 'ServicioController#obtenerServicios'));
Error
How I can get all that technical services?
First: it's best to use the Eloquent model to query instead of DB::table.
Eg:
$tecnico = Tecnico::with('servicio')->where('Auth_Token',$auth)->firstOrFail();
The DB query builder doesn't know the Eloquent relationships. Eloquent only knows the Query builder.
And second: don't pass access tokens in the URI. Not in a segment and not in the query string. Use headers for that.
Eg:
Route::get('servicio', 'ServicioController#obtenerServicios');
class ServicioController extends BaseController {
public function obtenerServicios() {
// strip the "Bearer " part.
$token = substr(Request::header('Authorization'), 0, 7);
// ...
}
}
Use Eloquent to get Eloquent results like Model::find() etc. (DB::table... will return stdObject, that's the error you get), and correct these relations:
// class Tecnico
public function servicios(){
// the keys are wrong:
// return $this->belongsToMany('Servicio', 'Servicio_Tecnico', 'idTecnico', 'idServicio');
// it should be like this:
return $this->belongsToMany('Servicio', 'Servicio_Tecnico', 'Tecnico_idTecnico', 'Servicio_idServicio');
}
// class Servicio
public function tecnicos(){
return $this->belongsToMany('Tecnico', 'Servicio_Tecnico', 'Servicio_idServicio', 'Tecnico_idTecnico');
}