Accessing The Laravel SQL Relationship without Local Key - php

I am new in Laravel. I have two models: User and Car. I wish to access the car data from the user entity in the controller, but I could not find how to do it. In addition, the database is fixed with the columns and the administrator refuses to do any change on it.
Here is the User model:
class User extends Model {
protected $primaryKey = 'idUser';
protected $fillable = [
'name', 'age', 'address', 'gender', 'phone', 'email'
];
}
And then this is my Car model:
class Car extends Model {
protected $primaryKey = 'idCar';
protected $fillable = [
'carNumber', 'carMachineNumber', 'type', 'model', 'year', 'idUser'
];
public user(){
return $this->belongsTo(User::class, 'idUser');
}
}
In the controller and the blade templates, I wish I can access the car data from the user entity. For example when I want to get the car type data then I would access it by:
$user->car->type
It would be even better if I will be able to access all of the cars a user has by this line of code:
$user->car->all();
How to make it possible? What should I add to the controllers without making any change to database? Thanks.

You don't have standard primary key id, so you will have to specify all the keys in the relationship (idCar).
Car model
public function user() {
return $this->belongsTo(User::class, 'idUser', 'idCar');
}
But this will get you $car->user which is the owner of the car.
With the way you designed your database, a user can have many cars.
User model
public function cars() {
return $this->hasMany(Car::class, 'idUser', 'idUser');
}
When you want to retrieve the cars belong to a user, you can
$user->cars;
or
foreach($user->cars as $car) {
// $car
}

Related

when register, insert data in 3 tables LARAVEL

I work at a project, I started to learn Laravel and I wanted to create a register form where you can put all your information and all the information to be sent in 3 tables.
You have to select if you are a candidate or a employer.
In my database i have those 3 tables: users, profile_employee and profile_employer.
Can someone show me how to create the RegisterController to insert in the table users only email and password, and if they selected candidate to send the rest of information to profile_employee, and if they selected employer to send them to the table profile_employer. Thanks!
This is are my models for ProfilasdasdasdasdasdasdasdasdasdeEmployeer and ProfileEmployee
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class ProfileEmployee extends Model
{
protected $table = 'profasdasdasdasdile_emploasdasdasdasdyee';
protected $fillable = [
'id','usasdasdasder_id', 'fiasdasdasdasdasdst_name', 'laasdasdst_namasdasdasdasdasde','phonasdasdasde', 'casdasdv', 'picasdasdasdasdture', 'adrasdasdasdasdasdess', 'toasdasdasdasdasdasdwn',
];
protected $hidasdasdasdasdasdden = [];
}
and
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class ProfileEmployer extends Model
{
protected $tablasdasdasdasde = 'profileasdasdasdasdasdasdasd_emplasdasdasdasdasdasdoyer';
protected $fillabasdasdasdasdle = [
'iasdasdasdd','useasdasdr_iasdasdasdasdasdasd', 'coasdasdasdasdasdmpany_naasdasdasdasdasdme', 'CasdasdasdU_asdasdI', 'phoasdasdasdasdasdne', 'pictasdasdasdasdasdure', 'adasdasdasdasdress', 'towasdasdasdasdasdn',
];
protected $hidasdasdasdden = [];
}
How can I do the RegistasdasdasdasdasdasdasderController?
Without writing any code I think the best way would be to create a polymorphic relationship, there’s some example code in the documentation-
https://laravel.com/docs/5.8/eloquent-relationships#one-to-one-polymorphic-relations
So in your users table you’d have a userable_type and userable_id (not sure if them names are correct). The userable_type column would contain the model name for either your ProfileEmployee table or your ProfileEmployer table and the userable_id the foreign key of the relationship.
As you can see in the documentation you can then retrieve the relationship and laravel will know which model to use by the userable_type column.
Looking at your tables though I think you could merge the profiles into one table and maybe have a metadata column for data which isn’t always stored for both user types.
I think you can do it by creating two separate method for user type to create them by passing user instance in RegisterControlle just like as follow. and dont forget to return user after creating profile.
class RegisterController extends Controller{
use RegistersUsers;
protected $redirectTo = '/home';
public function __construct()
{
$this->middleware('guest');
}
protected function validator(array $data)
{
return Validator::make($data, [
'name' => 'required|string|max:255',
'email' => 'required|string|email|max:255|unique:users',
'password' => 'required|string|min:6|confirmed',
'type' => 'required|in:employee,employer',
]);
}
protected function create(array $data)
{
$user = User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
]);
// check the user type
$data['type'] = 'employee' ? $this->createEmployee($user) : $this->createEmployer($user);
}
public function createEmployee($user)
{
// here you can create Employee profile
return $user;
}
public function createEmployer($user)
{
// here you can create Employer profile
return $user;
}
}
Here we need to overwrite two method which is validator and create.

How to create a relationship in laravel

Am new to laravel, I have issues trying to connect this tables: plans,users and loans even after reading the docs,
I have a plans tables that have all my plans, then I have a users table and loans table, my loans table has a user_id and a plan_id, all I want is to pull the records for plans and the users in the loan model.
Loanplan.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Loanplan extends Model
{
//
protected $fillable = [
'title',
'amount',
'interest',
'repayment_month',
'status',
];
public function loan()
{
return $this->belongsTo('App\loan');
}
}
my loan model:
Loan.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Loan extends Model
{
protected $table = 'loans';
//
protected $fillable = [
'id',
'user_id',
'loanplan_id',
'payment_made',
'status',
];
public function user()
{
return $this->belongsTo('App\User');
}
public function loanplan()
{
return $this->belongsTo('App\Loanplan');
}
}
I want get all the loan plans and users table records with plan_id and user_id as foreign respectively respectively in my LoanController.
I think the problem is with the customization of the loans table name in the Loanplan model.
According with your descriptions you need the followings setup:
A User can access to one or many Loans
users 1---m plans
A Loan belongs to a Loanplan // here I'm using Loanplan because that is your model name.
loans 1---m plans
So, this means:
User.php
namespace App;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
protected $table = 'users';
//
protected $fillable = [
'id',
//
];
public function loans()
{
return $this->hasMany(Loan::class);
}
//
}
Loan.php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Loan extends Model
{
protected $table = 'loans';
//
protected $fillable = [
'id',
'user_id',
'loanplan_id',
//
];
public function user()
{
return $this->belongsTo(User::class);
}
public function plan()
{
// Notice that here I'm specifying the foreign key:
return $this->belongsTo(Loanplan::class);
}
//
}
Loanplan.php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Loanplan extends Model
{
protected $table = 'plans';
//
protected $fillable = [
'id',
//
];
public function loans()
{
return $this->hasMany(Loan::class);
}
//
}
So with this, you can access the information in your LoanController.php:
LoanController.php
public function myCoolMethod()
{
// get a user
$user = User::first();
// access his/her loans
$loans = user->loans;
//
// get a loan plan
$plan = Loanplan::first();
// access its loans
$loans = plan->loans;
//
}
I strongly suggest you to read the Laravel Documentation regarding relationships and also a course for database design. Have a good day mate.
Loanplan.php is missing the protected $table = "plans" variable
Same file,
public function loan()
{
return $this->belongsTo('App\loan');
}
the relationship should be hasOne or hasMany, not belongsTo.
Moreover, the name of the class should have Loan with capital L.
public function loan()
{
return $this->...('App\Loan');
}
First of all add protected $table = 'plans'; to your Loanplan model since the table name is 'plans'
Loanplan Model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Loanplan extends Model
{
protected $table = 'plans';
protected $fillable = [
'title',
'amount',
'interest',
'repayment_month',
'status',
];
public function loan()
{
return $this->hasOne('App\loan'); // or hasMany
}
}
?>
Loan Model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Loan extends Model
{
protected $table = 'loans';
//
protected $fillable = [
'id',
'user_id',
'loanplan_id',
'payment_made',
'status',
];
public function user()
{
return $this->belongsTo('App\User');
}
public function loanplan()
{
return $this->belongsTo('App\Loanplan');
}
}
?>
add this to the User Model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
public function Loan()
{
return $this->hasOne('App\Loan'); // or hasMany
}
}
?>
First, you have to check if the model already querying from table that you created before. Laravel will automatically access table base on your class name.
Note that we did not tell Eloquent which table to use for our Flight model. By convention, the "snake case", plural name of the class will be used as the table name unless another name is explicitly specified. So, in this case, Eloquent will assume the Flight model stores records in the flights table.
You can read it from this documentation
Second, make sure you call the right class. From Loanplan.php in the loan() method it's not using uppercase for the first letter.
Third, try to state the foreign key and primary key. You can also check how to do it in the documentation.

AngularJS & Laravel 4.2 retrieving data from multip tables and joining them

I've recently started to work with Laravel and I just recently got help to insert the data into multiple tables from one controller. Now I'm trying to retrieve data from the database and populate the form if an edit is needed or if someone needs to look at the data to be able to confirm it is correct. I don't understand how I join the tables is this in the model in Laravel? Or do I have to create a join SQL query?
Travelbill.php Model
<?php
class Travelbill extends Eloquent {
protected $table = 'travelbill';
protected $primaryKey = 'TravelbillId';
protected $fillable = array('ResourceId', 'Destination', 'StartDay', 'StartTime', 'EndDay', 'EndTime', 'Invoice', 'TravelCompensation');
public $timestamps = true;
public function travelbill() {
return $this->belongsTo('User', 'ResourceId', 'ResourceId');
}
public function cost() {
return $this->hasOne('Cost', 'TravelbillId', 'TravelbillId');
}
public function allowance() {
return $this->hasOne('Allowance', 'TravelbillId', 'TravelbillId');
}
}
?>
Cost.php Model
<?php
class Cost extends Eloquent {
protected $table = 'cost';
protected $primaryKey = 'CostId';
// protected $fillable = array('TravelbillId', 'Description', 'DescriptionByHiq', 'SekInklMoms', 'SekExklMoms', 'SekInklMomsByHiq', 'SekExklMomsByHiq', 'Currency', 'ExchangeRate');
protected $fillable = array('TravelbillId', 'Description', 'DescriptionByHiq', 'SekInklMoms', 'SekMoms', 'SekInklMomsByHiq', 'SekMomsByHiq', 'Currency', 'ExchangeRate');
public $timestamps = false;
public function cost() {
return $this->belongsTo('Travelbill', 'TravelbillId', 'TravelbillId');
}
}
?>
Allowance.php Model
<?php
class Allowance extends Eloquent {
protected $table = 'allowance';
protected $primaryKey = 'AllowanceId';
protected $fillable = array('TravelbillId', 'DayAllowance', 'Breakfast', 'Lunch', 'Dinner');
public $timestamps = false;
public function allowance() {
return $this->belongsTo('Travelbill', 'TravelbillId', 'TravelbillId');
}
}
?>
Or where am i doing this join so if i get the travelbill it also gets the Cost and Allowance data with the request?
EDIT:
I need to get the data into my AngularJS form so if a person with id = 1 needs to edit his Travelbill he should be able to click a edit button and see the information ha has filled out.
The simplest form of data retrieval you can do here is to do the following:
$travelBills = Travelbill::with(['code','allowance'])->get();
This is Eager Loading and will perform three queries:
Load all the travel bills
Load all codes that have foreign keys matching all the travelbill ids and assign them to each travel model
Do the same with allowances
What you'll have in the end that every Travelbill model will already have an associated Code and Allowance model, allowing you to work like:
echo $travelBill->cost->SekInklMoms;
for one of the Travelbills you loaded. Note a couple of things in the first query:
The travelbills are not filtered, we are loading them all at this point.
We are doing it simply, not necessarily efficiently. I recommend first get comfortable with the relationships loading before get onto things like joins (which break the spirit of Eloquent ORM in any case)

Laravel Relation based on value within an JSON object

I have two models in which I need to relate to, a Users model and a Prices model. In my Prices model there is a JSON object which holds an ID of a user and I was wondering if I could relate to my Prices table using the ID which is in the Prices model?
I know you could use an getAttribute and then return the user like that, but I was wondering if there is a $this->hasOne() method you could use?
e.g.
JSON
{user_id: 1, other_values:"in the object"}
Prices Model
class Prices extends Model {
/* Prices has the column 'object' which has the JSON object above */
protected $casts = ['object' => 'array'];
public function user(){
return $this->hasOne("App\User", $this->object->user_id, "id"); /* ! Example ! */
}
}
I created a package with JSON relationships: https://github.com/staudenmeir/eloquent-json-relations
Since the foreign key is in the Prices model, you should use a BelongsTo relationship:
class Prices extends Model {
use \Staudenmeir\EloquentJsonRelations\HasJsonRelationships;
protected $casts = ['object' => 'array'];
public function user() {
return $this->belongsTo(User::class, 'object->user_id');
}
}
class User extends Model {
use \Staudenmeir\EloquentJsonRelations\HasJsonRelationships;
public function prices() {
return $this->hasMany(Prices::class, 'object->user_id');
}
}

Inserting two foreign keys to a pivot table after form submission using Laravel

I'm trying to create a resource provider database web app with a Resource, Location, ResourceLocation (pivot table), and ContactPerson models set up. I'm pretty sure I have the Model relationships set up correctly because from my Create A New Resource form it inserts the data into the database, it just doesn't show up in my view because the foreign keys (Resource_ID & Location_ID) aren't inserted into the pivot table. Here's the code I have so far.
Models
class Location extends Model
{
public function resource()
{
return $this->belongsToMany('App\Models\Resource', 'ResourceLocation');
}
}
class Resource extends Model
{
public function locations()
{
return $this->belongsToMany('App\Models\Location', 'ResourceLocation');
}
}
class ResourceLocation extends Model
{
protected $table = 'ResourceLocation';
public $timestamps = false;
protected $fillable = [
'Location_ID',
'Resource_ID'
];
}
Resource Controller
public function newResource(CreateNewResourceRequest $req)
{
$resource = Resource::create(Request::only(
'Name',
'Description',
'Misc_Info'
));
$location = Location::create(Request::only(
'Address',
'Address2',
'City',
'Zip_Code',
'County',
'Hours',
'Appt_Necessary'
));
$resource->save();
$resource->location()->attach($location);
\Session::flash('flash_message', 'Resource Created Successfully!');
return redirect('resource');
}
Once I hit the submit button on my form I get the error:
BadMethodCallException in Builder.php line 2345:
Call to undefined method Illuminate\Database\Query\Builder::location()
All the input from my form gets inserted into my database tables, but the ResourceLocation (pivot table) is left empty.
If I do $resource->$location()->attach($location['Location_ID']); it gives me a Method must be a string error. What am I doing wrong here? Any help would be greatly appreciated, thanks!
I figured it out, in my Resource Controller I have a location method:
public function location()
{
$locations = Location::all
return view (compact('locations'));
}
I changed my newResource method to:
public function newResource(CreateNewResourceRequest $req)
{
...
$resource->save();
$resource->locations()->attach($locations);
}

Categories