laravel create, delete, update hasMany with many fields - php

I'm new to laravel. I have 2 table
class Client extends Model
{
protected $fillable = ['name'];
public function clientmoreinfo()
{
return $this->hasMany('App\Moreinfoclient');
}
}
class Moreinfoclient extends Model
{
protected $table = 'clients_additionalfield';
protected $fillable = ['client_id', 'nameinput', 'valueinput'];
public function clients()
{
return $this->belongsTo('App\Client');
}
}
and i need to be able to add many additional fields at once as seen here:
this is how I add any number of entries, and more importantly, how do I update or remove them later?
thank you all in advance !

Related

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 - using inRandomOrder() on belongsToMany RelationShips

in this code as:
$latestHerbsInformation = \App\ContentCategories::find('14')->contents->take(5);
which that work fine i want to use inRandomOrder() to get random rows from contents, Contents and ContentCategories are belongsToMany RelationShips and this code:
$latestHerbsInformation = \App\ContentCategories::find('14')->contents->inRandomOrder()->take(5);
don't work for me.
Contents model:
class Contents extends Model
{
use Sluggable;
protected $table = 'contents';
protected $guarded = ['id'];
public function categories()
{
return $this->belongsToMany(ContentCategories::class);
}
}
ContentCategories model:
class ContentCategories extends Model
{
protected $table = 'contents_categories';
protected $guarded = ['id'];
public function contents()
{
return $this->belongsToMany(Contents::class);
}
}
i get this error:
Method inRandomOrder does not exist.
how can i solve this problem? Thanks in advance
The correct query is:
\App\ContentCategories::find('14')->contents()->inRandomOrder()->take(5)->get();
Because this will execute the query and will return a collection:
\App\ContentCategories::find('14')->contents

Laravel 5.2 three-way pivot with custom pivot model

I have the following problem:
I have three tables:
contacts (people)
departments
contact_types (e.g. IT-Contact)
All of them are many-to-many types; One person can be a responsible for 0-n departments as 0-n Contact_types (even for the same department as multiple types). And so on.
In addition i have to have a history all over the project, so each of the tables stores "valid_start" and "valid_end" timestamps as well.
Therefore i now have this relation table:
contact_contact_type_department
id
contact_id
contact_type_id
department_id
valid_start
valid_end
What i ended up doing is creating a Model for the intermediate table:
class DepartmentResponsible extends Model {
protected $table = 'contact_contact_type_department';
protected $fillable = [...];
protected $dates = [
'valid_start',
'valid_end',
];
protected static function boot(){
parent::boot();
static::addGlobalScope(new ValidScope());
}
public function contact() {
return $this->belongsTo('cap\Contact');
}
public function department() {
return $this->belongsTo('cap\Department');
}
public function type() {
return $this->belongsTo('cap\ContactType');
}
}
Contact Model:
class Contact extends CustomModel{
protected $dates = [...];
protected $fillable = [...];
protected static function boot(){
parent::boot();
static::addGlobalScope(new ValidScope());
}
public function departmentResponsibles() {
return $this->hasMany('cap\DepartmentResponsible');
}
}
ContactType Model:
class ContactType extends CustomModel {
protected $dates = [...];
protected $fillable = [...];
protected static function boot() {
parent::boot();
static::addGlobalScope(new ValidScope());
}
public function responsible() {
return $this->hasMany('cap\DepartmentResponsible');
}
}
Department Model:
class Department extends CustomModel {
protected $fillable = [...];
protected $dates = [...];
protected static function boot(){
parent::boot();
static::addGlobalScope(new ValidScope());
}
public function responsibles(){
return $this->hasMany('cap\DepartmentResponsible');
}
//other methods down here, which have no immpact on this issue
}
I can now do things like
Department::first()->responsibles
Regarding the issue with the timestamps on the pivot table i assume i will have to make it a custom pivot table again (already had to do that once, in another case, where i had a "regular" 2-way pivot table)
So my 2 Questions now are:
1. Is this even the right way to do it? I mean the whole thing with the intermediate model and so on. I tried other ways as well, but I couldn't get anything like department->attach(contact) to work since i always need the third id as well...
2. How can i get something like Department::first()->contacts to work? (In a way, where i can access the intermediate "responsibles (=contact_contact_type_department)" table and filter based on the validity dates;eg. with a scope or with wherepivot functions)
well i finally went with the approach that i have an intermediate model called responsible. So for example if i want to print all the contacts and their contact_types for a department then i can do something like this:
$department = Department::first();
<ul>
foreach($department->responsible as $responsible){
<li>{{$responsible->contact->name}} as {{$responsible->type->name}}</li>
}
</ul>

Obtaining a list of non-linked models, in many_to_many relations, using Laravel Eloquent

I have a User-Roles model, using Laravel 4 where a user can have many roles, using Eloquent. I can access all roles linked to a user easily using this code :
class User extends Model {
protected $table = 'user';
protected $fillable = array('name');
public function rolesLinked() {
return $this->hasMany('App\UserRoleLink', 'user_id');
}
}
I've been trying to obtain the roles that are not linked to a user, to display on the specific user's page in a select box. Using this function, included in the User class.
public function rolesNotLinked() {
$user = this
$roles = Roles::whereDoesntHave('App\UserRoleLink',function($query) use ($user){
$query->where('user_id',$user->id);
});
}
The problem is, calling this function gives me the following error.
Call to undefined method Illuminate\Database\Query\Builder::App\UserRoleLink()
I've tried using has with < 1 to see if the function was problematic, but after reading this and the online source code, the function call pretty much does what I've tried.
Is something wrong in my function call, or have I messed up configurations somewhere?
For reference, here are my other Model classes:
class UserRoleLink extends Model{
protected $table = 'user_role_link';
protected $fillable = array('role_id','user_id);
public function role() {
return $this->hasOne('App\Role', 'role_id');
}
}
class Role extends Model{
protected $table = 'role';
protected $fillable = array('name');
}
EDIT: I've found out that I messed up by fillables when I copy-pasted. It didn't fix the issue, but I guess that's one step closer.
To use whereDoesntHave method, you must add the relation in your Role Model.
class Role extends Model{
protected $table = 'role';
protected $fillable = array('name');
public function UserRoles() {
return $this->hasMany('App\UserRoleLink', 'id');
}
}
Also, the whereDoesntHave method first parameter is not thte model but the function of the relation:
public function rolesNotLinked() {
$user = this
$roles = Roles::whereDoesntHave('UserRoles',function($query) use ($user){
$query->where('user_id',$user->id);
});
}

How to insert data using relation?

I have two table
posts
id|post_title|post_content
post_images
id|images|post_id
Controller
public function AddPost(Request $request)
{
Post::create($request->all());
// PostImage::create();
return Redirect::to('Post');
}
Also i have added Relation
class Post extends Model
{
protected $table = 'posts';
public function images()
{
return $this->hasMany('App\PostImage');
}
}
class PostImage extends Model
{
public function post()
{
return $this->belongsTo('App\Post');
}
}
I have one form where i adding post title ,post content and selecting multiple images. My question is how I can store post images along with post id in post_images table?
Rewrite your code like this
class Post extends Model
{
protected $table = 'posts';
//add $fillable here
protected $fillable = ['post_title', 'post_content'];
public function images()
{
return $this->hasMany(App\PostImage::class);
}
}
class PostImage extends Model
{
protected $table = 'post_images';
//add $fillable here
protected $fillable = ['images', 'post_id'];
public function post()
{
return $this->belongsTo(App\Post::class);
}
}
Now in your controller
Post::create($request->all())->images()->create($request->all());
Here Post create saves your data to db also returns the object then
you accesses the relation images and saves data to images.
See here for more details One To Many

Categories