Laravel 5 update without id - php

I have a problem in Laravel 5. When I update a record in database, I get error Unknown column 'id' in 'where clause'. In the controller, I use WHERE clause to get the record I want to update. My primary key is not id and the type is bigInteger. I've tried adding protected $primaryKey in the model but it doesn't work for bigInteger. Is there any way to use my own primary key instead of using id?
Controller
$item = Item::where('item_id','=',$item_id)->first();
$item.name = $name;
$item.type = $type;
$item.save();

pls add this line to your Item.php model
class Item extends Model {
// add this line only
protected $primaryKey = 'item_id';
//..... the rest of your model
since your using custom id name, laravel will not know what is your primary key without you specify it

Laravel's orm $primaryKey default is 'id'.
When orm update, it use the sql like:
... where {$this->primaryKey} = {$this->{$this->primaryKey}}
So when you class extends orm.
You should redefine protected $primaryKey = '<your_table_primary_key>';.

Try this $item = Item::where('item_id', $item_id)->first(); If still don't working add also protected $primaryKey = "item_id"; to your model

Related

Getting wrong data from database even if I am fetching something different in laravel api

Hello guys I am working on a laravel project for making api for passing the database value in json format but the problem is I have a users table in this table 2 ids 1 is primary key and second is business _id I want to get data according to business_id but it's getting data by id please help me how to solve this issue.
Here is my model code
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class user extends Model
{
protected $table = 'business';
}
Here is my Controller Code
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\user;
class GetController extends Controller
{
public function databybusinessid($business _id){
$users = new user();
$users = user::find($business _id);
return response()->json($users);
}
}
Thank you so much
You are using user::find($business _id)
find() method will automatically search by the primary key but none is defined in your model and Eloquent can't decide which one to pick from your table. Therefore, you should explicitly set your primary key in your model by adding the following line.
class user extends Model
{
protected $table = 'business';
protected $primaryKey = 'business_id';
}
If in doubt, you can also fetch database record by a specific column using where
$users = user::where('business_id', '=', $business _id)->get()
Laravel documentation about Eloquent ORM
https://laravel.com/docs/5.8/eloquent
find() Retrieve a model by its primary key..
So you have to use your code as:
$users = user::where('business_id',$business_id)->first();
// Notice first() Retrieve the first model matching the query constraints...
Or you can change your primary code in model
namespace App;
use Illuminate\Database\Eloquent\Model;
class user extends Model
{
protected $table = 'business';
protected $primaryKey = 'business_id';
}
find() works only on primary key. you need to use where instead.
or you can define business_id as primary key in your User model.
protected $primaryKey = 'business_id';
public function databybusinessid($business _id){
$users = new user();
$users = user::where('business_id',$business _id)->first();
return response()->json($users);
}

Custom Model and fields with Sentinel / Laravel

I', integrating a new system to an existing database.
So, my User table doesn't have default fields names.
All names are in spanish, so, Sentinel looks for email when he should look for "correo"
Also, when executing
Sentinel::check(),
I get this message error:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'administrador.id' in 'where clause' (SQL: select * from `administrador` where `administrador`.`id` = 1 and `administrador`.`deleted_at` is null limit 1)
In fact, id doesn't exists, the PK is called administradorid
The only resource I found is a very quick one:
https://github.com/cartalyst/sentinel/wiki/Extending-Sentinel
It says it is extremly easy, but do not mention this case.
So, basically, how can I customize all the fields name of the Sentinel Model???
Here is my model:
class Administrador extends EloquentUser {
protected $table = 'administrador';
protected $fillable = [];
protected $guarded = ['administradorid'];
protected $hidden = ['contrasena', 'remember_token'];
use SoftDeletes;
protected $dates = ['deleted_at'];
}
Any help will be appreciated!
First, the id issue is a basic Laravel Eloquent issue. If the primary key for your model is not id, then you need to set the $primaryKey property on your model to the correct field name. Additionally, if your primary key is not an autoincrementing integer, then you need to set the $incrementing property to false, as well.
For the email issue, that is a Sentinel specific issue. The EloquentUser class has a $loginNames property that is set to an array of valid field names that contain user logins. The default is just ['email'], so you need to override this property and change it to your field name.
So, your Administrador class ends up looking like:
class Administrador extends EloquentUser {
use SoftDeletes;
protected $table = 'administrador';
protected $primaryKey = 'administradorid';
//public $incrementing = false; // only if primary key is not an autoinc int
protected $fillable = [];
protected $guarded = ['administradorid'];
protected $hidden = ['contrasena', 'remember_token'];
protected $dates = ['deleted_at'];
// Sentinel overrides
// array of fields that hold login names
protected $loginNames = ['correo'];
}

Laravel: How to add a composite key (2 or more columns) as the $primaryKey in the related model?

Name of the primary key column in any model in Laravel framework is id
protected $primaryKey = 'id';
And I know I can change that default name like this:
protected $primaryKey = 'new_name';
My question is: What if I have a composite key (2 or more columns) in the table, how do I add them as the $primaryKey? And do I really have to define them?
From the Laravel docs:
$table->primary(array('first', 'last'));
Edit: I misunderstood the question. This thread might provide some answers: http://forumsarchive.laravel.io/viewtopic.php?pid=34475
Specifically overriding the find() method.
public static function find($primaryOne, $PrimaryTwo) {
return Widget::where('primaryOne', '=', $primaryOne)
->where('PrimaryTwo', '=', $PrimaryTwo)
->first();
}

Laravel: static::create vs DB:insert

If I use the following code snippet in my model it inserts the data:
$instance = DB::table('users')->insert(compact('email', 'username'));
But if I do this instead:
$instance = static::create(compact('email', 'username'));
It inserts null, but created_at and updated_at are inserted.
Laravel's created_at/updated_at are part of Illuminate\Database\Eloquent\Model. A raw DB::table query builder isn't an Eloquent model and thus doesn't have those automatic parameters.
NULL data is being inserted in the Eloquent query because Eloquent has a $fillable parameter you need to define. This parameter sets which columns can be mass-assigned. Laravel strips attributes not in this array when you do a fill, create, or otherwise instantiate a new object. In your model, you'd want:
class User extends Eloquent {
protected $fillable = ['email', 'username'];
}
ceejayoz answer is great, here's an explanation of how to call the model. Once the model is created, let's say this model:
class User extends Eloquent {
protected $fillable = ['email', 'username'];
}
Then you need to call by using the model directly and eloquents ORM like so:
// example is this. True method is TableName->ColumnName = Value;
$user = User::find($id);
$user->username = '';
$user->fullname = '';
$user->save();
The save will update the columns based on what you describe. With this you don't even need the fillable variable.
Some other variables for models that are good to know is:
protected $primaryKey = 'userid'; #if you have an primarykey that isn't named id
protected $table = 'tablename'; #if table name isn't pulling by the name of the model
protected $timestamps = true; #bool value, whether u have timestamp columns in table
You said us that you done
class User extends Eloquent {
protected $fillable = ['email', 'username'];
}
however in your comment you told us you got the following error in your apache log
SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry ''
for key 'users_email_unique' (SQL: insert into ``users
(updated_at, created_at``) values (2015-01-06 21:52:35, 2015-01-06 21:52:35))
Make sure to also include users_email_uniquein your fillable array if you want to set it.
class User extends Eloquent {
protected $fillable = ['email', 'username', 'users_email_unique'];
}

Storing and Fetching more than one table from a Single Model

Here is my Model
<?php
class VehicleModel extends Eloquent
{
protected $primaryKey = 'AutoID'; # to change the primary key else laravel will consider id as primary key
protected $table = 'vehicle';
}
Using this i can fetch
$vehiclelist = VehicleModel ::all();
But i need to fetch another table from the same model
Is it possibel to have something like this
<?php
class VehicleModel extends Eloquent
{
protected $primaryKey = 'AutoID'; # to change the primary key else laravel will consider id as primary key
protected $table = 'vehicle';
protected $secondtable = 'route';
}
And should be accessible by
$routelist= Detail::make(VehicleModel ::$secondtable );// This is the thing i am doing wrong
Is it possible in this way if not how can i do this so that i should be able to fetch the details from same model .
Note :
I can't create seperate model for each table because i need to fetch many (different) tables for each form
If you have multiple tables that are different things (not multitable inheritance) you really should create a model for each table. It isn't that much work but will make things a lot easier.
For the following example, let's assume that one vehicle can have many routes. And in the database you VehicleID in the route table referencing AutoID in the vehicle table.
Then you can add these two relations inside your models
VehicleModel
public function routes(){
return $this->hasMany('RouteModel', 'VehicleID');
}
RouteModel
public function vehicle(){
return $this->belongsTo('VehicleModel', 'VehicleID');
}
Now here are some examples how to use it:
$vehicle = VehicleModel::find(1);
$routesOfVehicle1 = $vehicle->routes;
$route = RouteModel::find(1);
$vehicleOfRoute1 = $route->vehicle;
$allVehiclesIncludingTheirRoutes = VehicleModel::with('routes')->get();
For more information, read the Laravel Docs on Relations
Why don't you extend VehicleModel class?
I think there is no way except extend.
<?php
class VehicleModel extends Eloquent
{
protected $primaryKey = 'AutoID'; # to change the primary key else laravel will consider id as primary key
protected $table = 'vehicle';
}
class RouteModel extends VehicleModel
{
protected $table = 'route';
}
class StuffModel extends VehicleModel
{
protected $table = 'stuff';
}
?>

Categories