laravel Eloquent ORM custom field name - laravel

I am trying to get record from a products table with the field productsid by using Eloquent and using the following code. My model name is Products_description.
In my route file.
Route::get('product/{productsid}','productscontroller#show');
In my controller file
public function show($productid)
{
$Products = Products_description::find($productid);
return $Products;
}
But it showing me the error that Unknown column 'products_description.id'. Looks like Eloquent try to get record through the field name id by default like it do with the table names. But how to get records through a table field other than id. e.g. if it is productid, what we would do/use?

In your model, declare your $primaryKey
class Products_description {
protected $primaryKey = "productid";
//
}
This way you can use ::find or firstOrFail and not where.

like this
$Products = Products_description::where('pruductid',$productid)->first();
or you can try this
Products_description model
class Products_description extends Eloquent {
protected $primaryKey = 'productid';
}

I am assuming your need is to query your table for a field other than the primary key . You can use:
Products_description::where('productid',$productId)->first()
If you are speaking about foreign keys, then you should define them in the model like so :
return $this->hasOne('App\Phone', 'foreign_key');
Here is the relevant documentation :
https://laravel.com/docs/5.1/eloquent-relationships#one-to-one

Related

laravel eloquent migrations

In laravel eloquent relationship, is it still necessary to make migration even though there's an existing database? beginners here.
I create a one-to-one eloquent relationship inside my model to get the specific column from another table's record and fetch to the datatable, but it did not work.
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Directorystatus extends Model
{
use HasFactory;
protected $table = 'user_status';
protected $fillable = ['status_id' , 'status_xtitle'];
public function userbasic() {
return $this->belongsTo(directorybasic::class,'user_xusern','status_xuser');
}
}
class Directoryuser extends Model
{
use HasFactory;
protected $table = 'user_basic';
protected $primaryKey = 'user_id';
protected $fillable = ['user_id' , 'user_xusern' , 'user_xfirtname' ,'user_xmiddlename','user_xlastname'];
public function userstatus() {
return $this->hasOne(directorystatus::class,'user_xusern','status_xuser');
}
}
No. Migrations are not necessary. Defining relationships on both sides is also not necessary, if you don't need them both. (You can have only belongsTo, without having hasOne or hasMany in the opposite model.)
First, make sure you are using the right object (Directorystatus::class / Directoryuser:class - I see they're not capitalized in your code). The next param is the foreign key, meaning the column which points to a model's primary key. The third param is optional and is used only if the primary key is not id.
For example if you have a column status_xuser in the table user_status, which contains a user_id from user_basic table, you should define it like this:
public function userbasic() {
return $this->belongsTo(Directoryuser::class,'status_xuser','user_id');
}
And in order to use this relationship, when you retrieve a model from the db, for example, you should call on it the same way your relationship function is named.
$status = Directorystatus::find(1);
$user = $status->userbasic();
I would also suggest you name your classes in camelCase, because it's the accepted practice (in Laravel especially).

How to select specific column in eloquent relationship inside the Model?

EDITED: Guys can you review your suggested duplicate? I did some research before I ask this question, and I'm already to that link, that is not the answer that I'm looking for.
How can I pluck specific column in eloquent relationship? I want only name column to be returned when I Student::find()->subject;
I tried the below codes but doesn't work and returns me an error
App\Student::subject must return a relationship instance.
class Student extends Model
{
protected $table = 'subjects';
protected $fillables = ['id', 'name', 'gender', 'birthdate', etc.];
public function subject()
{
return $this->hasMany('App\Subject')->pluck('name');
}
}
You can use any query builder functions on the relation.
Use select to only select the name column
public function subject()
{
return $this->hasMany('App\Subject')->select('name');
}

How the save autoincrement values using laravel eloquent

I am trying to save data into a database using Laravel eloquent models. However, the primary key is an auto-increment integer and it's throwing an error:
SQLSTATE[HY000]: General error: 1364 Field 'property_valuation_id' doesn't have a default value.
Any help on how this can be solved.
Here is the controller:
public function index(Request $request)
{
$property_valuation = new PropertValuation();
$property_valuation->property_valuation_id="";
$property_valuation->integer('property_valuation_id')->default(1);
$property_valuation->district_id = $request->input('district');
$property_valuation->propertyneighbourhood = $request->input('neighborhood');
$property_valuation->propertystreet = $request->input('street');
$property_valuation->numberofbedrooms =$request->input('bedrooms');
$property_valuation->currency=$request->input('currency');
$property_valuation->monthlyrent=$request->input('rent');
$property_valuation->save();
}
And here the model:
class PropertValuation extends Model
{
protected $table = 'property_valuation';
public $primaryKey = 'property_valuation_id';
public $timestamps = false;
}
You're overwriting Laravels default behaviour with this lines
$property_valuation->property_valuation_id="";
$property_valuation->integer('property_valuation_id')->default(1);
Remove it and it should be ignored within the SQL query and the auto-increment value should be set.
First of all you should use
$table->bigIncrements('property_valuation_id');
or
$table->increments('property_valuation_id');
in your migration file and then run in console php artisan migration:fresh to update your db structure. Aslo your why you are using custom field increment name instead of default 'id' ?
Second you must do is to set value for fillable variable in your Model. No need to include autoincrement field in this array.
protected $fillable = ['neighborhood', 'district',.....];
And the last thing. It is unnessessary to set all values for model from request, laravel do it itself. So your controller store method might be
public function store(Request $request)
{
PropertValuation::create($request->all());
return redirect()->back();
}
Much cleaner, yeah? :)

How to convert sql query to eloquent in laravel

how to convert sql to eoquent
$getAllRequirementRecord = Requirement::select()
->join('requirement_locations','requirements.id','=','requirement_locations.requirement_id')
->join('locations','requirement_locations.location_id','=','locations.id')
->where('isdelete',2)
->where('requirements.id',$id)->get();
help to solve this problems
Let's say we've an eloquent Model named Requirement and we've a database table named requirements associated with that model and we have another model named requirementLocation associated with a database table named requirement_locations.
and we have a database relation ship between both tables "requirements" & "requirement_locations" based on the requirement_id
Requirement Model:
class Requirement extends Model{
protected $table = 'requirements';
}
RequirementLocation Model:
class RequirementLocation extends Model{
protected $table = 'requirement_locations';
}
and Now we need to setup a relationship between these two models like the database tables .. so inside the Requirement we're gonna use has many relationship
use App\RequirementLocation;
class Requirement extends Model{
protected $table = 'requirements';
public function locations(){
return $this->hasMany(RequirementLocation::class);
}
}
and simply to fetch your data use
$id = 1;
$getAllRequirementRecord = Requirement->whereHas('locations' , function($query){
$query->where('isdelete',2);
})->where('id',$id)->with('locations')->get();
You can use eloquent with SQL raw query likewise:
$activeusers = User::selectRaw('users.name, count(*) submitted_games')
->join('games', 'games.user_id', '=', 'users.id')
->groupBy('users.name')
->orderBy('submitted_games', 'DESC')
->get();
To output to the screen the last queries ran you can use this :
dd(DB::getQueryLog());
I hope you have created Requirement, Location and RequirementLocation models
So first add this code in Requirement.php model file:
public function locations()
{
return $this->hasMany('RequirementLocation', 'requirement_locations');
}
Then access the requirements like this :
$requirement = Requirement::where('id', $requirement_id)->first();
Now you can access locations like this :
$requirement->locations;

Issue with Laravel hasMany relation

I’m having an issue with relations in two of my models in a Laravel application. My models are:
class Invoice extends Eloquent {
protected $table = 'invoices';
public function line_items()
{
return $this->hasMany('LineItem');
}
}
And:
class LineItem extends Eloquent {
protected $table = 'line_items';
public function invoice()
{
return $this->belongsTo('Invoice');
}
}
In my controller, I fetch an Invoice row with the following:
$invoice = Invoice::find($id);
However, if I try and access the line_items property to fetch the LineItem rows relating to my invoice, I get the following error:
Invalid argument supplied for foreach()
Why is this? I’ve set my models up as per Laravel’s documentation: http://laravel.com/docs/eloquent#one-to-many
change
public function line_items()
for
public function lineItems()
and it will work , tested in Laravel 4.1 :)
Check your tables relations... (Schema)
Your FK must be lineitem_id... You have modified this? Laravel will configure automatically... Don't change this...
Then, try
$invoice->line_items() or $invoice->line_items in 4.1
Check for line_items before the foreach loop:
if(! $invoice->line_items->isEmpty()){
foreach($invoice->line_items as $line_item){
//do stuff
}
}
Also, it won't hurt to explicitly mention the FK, although laravel will automatically try to do it for you provided you use proper names for your table fields.
//Invoice Model
return $this->hasMany('LineItem', 'invoice_id');
//LineItem Model
return $this->belongsTo('Invoice', 'invoice_id');

Resources