pivot table in laravel 4 insertion - laravel-4

hey guys im new in laravel and i was trying to insert into my pivot table. i have this structure in my database
the departments table belongs to many categories and same as category so i have this models
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableInterface;
class Departments extends Eloquent {
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'departments';
protected $fillable = ['department_name'];
public $timestamps = false;
/**
* The attributes excluded from the model's JSON form.
*
* #var array
*/
public function categories()
{
return $this->belongsToMany('Categories');
}
}
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableInterface;
class Categories extends Eloquent {
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'categories';
protected $fillable = ['name'];
public $timestamps = false;
/**
* The attributes excluded from the model's JSON form.
*
* #var array
*/
public function department()
{
return $this->belongsToMany('Departments');
}
}
then i have a query in my controller like this
$messages = array(
'required' => 'Please Fill the required field',
'unique' => 'Name Already exist'
);
$catName = Input::get('categoryName');
$deptId = Input::get('deptId');
$validation = Validator::make(Input::all(),[
'categoryName' => 'required|unique:categories,name' ], $messages);
if($validation->fails()){
return array('error' =>$validation->messages()->all() );
}else{
$findDepartment = Departments::find($deptId);
$saveCat = $findDepartment->categories()->insert(array('name' => $catName));
}
but then when i checked the tables it adds up on the categories table but nothing is added in the category_department. do i miss any codes? and also i had an error last time I was trying to migrate my pivot table the error was this.
can you help me guys on what i am missing? tnx for the help in advanced.

First, you should name your model classes as singular: Category, Department.
Then try to declare your relationships with the pivot table name:
public function categories()
{
return $this->belongsToMany('Category', 'category_department');
}
and
public function departments()
{
return $this->belongsToMany('Departments', 'category_department');
}
now, to insert new data, try attach:
$findDepartment = Department::find($deptId);
$category = Category::where('name', '=', $catName)->first();
$saveCat = $findDepartment->categories()->attach($category->id);

Related

getting error when applied WHERE clause on a model(parent) and then gets its related model(child) data in eloquent

I have a User model which is a parent and Project model which is a child. I created a one-to-many relationship between these two like below.
User Model:
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'username', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
public function projects(){
return $this->hasMany('App\Project', 'user_id');
}
}
Project Model:
class Project extends Model
{
// Table Name
protected $table = 'projects';
//Primary Key
protected $primaryKey = 'project_id';
// Timestamps
public $timestamps = true;
protected $guarded = [];
public function user(){
return $this->belongsTo('App\User', 'user_id');
}
}
when applying where clause on user model and then getting its related projects:
class HomeController extends Controller
{
public function createProject(Request $request){
$client = User::where('email', $request->input('client'))->projects;
}
}
getting error
Exception
Property [projects] does not exist on the Eloquent builder instance.
but when doing
$client = User::find(id)->projects;
above query is giving me results.
Result Expected: i want to get the User model data by WHERE() clause instead of Find() clause and then gets its related projects.
As the Error Says that you dont have property in the Builder
$client = User::where('email', $request->input('client'))->projects;
try this
$client = User::with('projects')->where('email', $request->input('client'))->first()->projects;
here we are getting the user with the specific email and loading the realtion and here you get the relation as object
The source of your issue is that you have not yet retrieved any users. Before calling first() or get() on the query builder, you are limited to functions of the query builder.
Short version: call first() before accessing the projects
$client = User::query()
->where('email', $request->input('client'))
->first()
->projects;
Optional: add with('projects') to eager load the projects. This doesn't add any performance bonus in your case though, as you are only loading a single model.
class HomeController extends Controller
{
public function createProject(Request $request){
$client = User::with('projects')->where('id');
}
}
In HomeController this line will retrun collection of array.... In simple words it will return multiple records....
$client = User::where('email', $request->input('client'))->projects;
As you want single record use first (). To retrive single record... It will retrun first matching record...
$client = User::where('email', $request->input('client'))->first()->projects;

Laravel Relationship Issues : Laravel 5.4

I have 2 tables in my application... Users Conventioners
I have users id in the conventioners table and i want to access their genders from the Users table....
I have like 10 user ids in the conventioners table and 20 users in the users table...
Please how do I access all their genders in the users table...
$conventioners->users()->gender
Conventioners is an instance of the Conventioner Model which contains a relationship **belongsToMany
Thanks alot guys
Here is my Conventioner Model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Conventioner extends Model
{
/**
* #var string
*/
protected $table = 'conventioners';
/**
* #var array
*/
protected $fillable = [
'user_id','year','church_id','convention_id'
];
/**
* #return \Illuminate\Database\Eloquent\Relations\BelongsTo
*/
public function user()
{
return $this->belongsTo('App\User');
}
/**
* #return \Illuminate\Database\Eloquent\Relations\HasMany
*/
public function users()
{
return $this->hasMany('App\User');
}
/**
* #return \Illuminate\Database\Eloquent\Relations\BelongsTo
*/
public function convention()
{
return $this->belongsTo('App\Convention');
}
}
Here is my ConventionController method called Convention...
It retrieves the details for the current convention
public function convention($slug)
{
if(!$this->admin()) return redirect()->back();
$convention = Convention::where('slug', $slug)->first();
$participants = Conventioner::where('convention_id', $convention->id)->get();
$conventioner = [];
foreach($participants as $participant)
{
$thisUser = [];
$thisUser['data'] = User::withTrashed()->where('id', $participant->user_id)->first();
$thisUser['convention'] = $participant;
array_push($conventioner, $thisUser);
}
var_dump($participants->users()->pluck('gender')->all());
return view('dashboard/conventions/convention', [
'convention' => $convention,
'user' => Auth::user(),
'conventioners' => $convention->conventioners(),
'participants' => $conventioner
]);
}
The problem is that users is a collection not an individual that you can call gender on. If you want a list of all the genders you can use the following:
Conventioner::where('convention_id', $convention->id)->with('users')->get()
$conventioners->pluck('users')->pluck('gender')->all();
This will return an array of the genders. You can read more about pluck here.
The pluck method retrieves all of the values for a given key

How to relate two tables in Laravel 5.0

In a little example, I have 3 tables (2 of them are important).
My tables are PRODUCT, TRANSFER, WAREHOUSE
I want to transfer the PRODUCT from 1 WAREHOUSE to another and obviously this transfer has to be in the TRANSFER TABLE, My example model could be the next.
HERE THE ENTITY - RELATION - MODEL
Now I'm Using Laravel 5.0
And when I create the models im doing this, with TRANSFER model:
<?php namespace Sicem;
use Illuminate\Database\Eloquent\Model;
class TRANSFER extends Model{
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'TRANSFER';
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = ['id','ware_ori_id','ware_end_id','product_id'];
public function product(){
return $this->belongsTo('Sicem\Product');
}//THIS IS OK!
public function sourceware(){
return $this->belongsTo('Sicem\Warehouse\ware_ori_id');
}//I THINK THIS IS OK!
public function endware(){
return $this->belongsTo('Sicem\Warehouse\ware_end_id');
}//I THINK THIS IS OK!
}
Now, My question is here in my WAREHOUSE model, I don't what can I put:
<?php namespace Sicem;
use Illuminate\Database\Eloquent\Model;
class WAREHOUSE extends Model{
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'WAREHOUSE';
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = ['id','name'];
public function transfer(){
return $this->hasMany('Sicem\TRANSFER');
}//I supose this.
//But is or not necesary to have 2(two) functions for the relation in my TRANSFER model???????????
}
SICEM: is my project name
Please Help me.
class Product {
protected $table = 'PRODUCT';
protected $fillable = ['name'];
public function transfers()
{
return $this->hasMany(Transfer::class);
}
public function transfer($warehouse_from_id, $warehouse_to_id)
{
return Transfer::create([
'product_id' => $this->id,
]);
}
}
class Transfer {
protected $table = 'TRANSFER';
protected $filalble = ['ware_ori_id', 'ware_end_id', 'product_id'];
public function warehouse_from()
{
retrun $this->belongsTo(Warehouse::class);
}
public function warehouse_to()
{
return $this->belongsTo(Warehouse::class);
}
public function product()
{
return $this->belongsTo(Product::class);
}
}
class Warehouse {
protected $table = 'WAREHOUSE';
protected $fillable = ['name'];
}
So you need to do something like this:
$warehouseFrom = Warehouse::find(1);
$warehouseTo = Warehouse::find(2);
$product = Product::find(23);
$product->transfer($warehouseFrom->id, $warehouseTo->id);

Eloquent ORM all() not returning anything

Shoot me down if I this is a silly question, but I am really struggling to get this all() function working for me. It is returning empty list for me. Any help will be highly appreciated. I have got 2 rows in the newsletters table
Model looks like this -
<?php
use Illuminate\Auth\UserTrait;
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableTrait;
use Illuminate\Auth\Reminders\RemindableInterface;
class Newsletters extends Eloquent {
//use UserTrait, RemindableTrait;
use SoftDeletingTrait; // <-- Use This Insteaf Of protected $softDelete = true;
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'newsletters';
/**
* The attributes excluded from the model's JSON form.
*
* #var array */
protected $guarded = array('newsletterId');
protected $fillable = array('name', 'subject','from_email','from_name');
public static $rules = array(
'name' => 'required|min:5',
'subject' => 'required|min:5',
'from_email' => 'required|email',
'from_name' => 'required'
);
}
My call in the controller is like this -
<?php
class newslettersController extends \BaseController {
/**
* Display a listing of the resource.
*
* #return Response
*/
public function index()
{
//$newsletters = Newsletters::paginate(3);
$newsletters = Newsletters::all();
echo $newsletters;exit();
return View::make('newsletters.index', compact('newsletters'));
}
Any value - even 0000-00-00 00:00:00 - in the deleted_at column tells Laravel that the item has been deleted. Change your default value for that column to NULL or new items will be flagged as deleted on creation.
The $table->softDeletes() Schema function does this automatically if you use it in a migration.
As soon as you use the SoftDeletingTrait a global scope will be applied to every query with your model so all records where deleted_at is not NULL will be ignored.
Illuminate\Database\Eloquent\SoftDeletingScope:
public function apply(Builder $builder)
{
$model = $builder->getModel();
$builder->whereNull($model->getQualifiedDeletedAtColumn()); // <<-- this
$this->extend($builder);
}
Change the default of your deleted_at column to NULL and update the existing records to be NULL as well.
If you are sure newsletters is the correct table name as #Ray said.
Try this:
$newsLetters = DB::table('newsletters')->get();

Can't make a new Insertion - Laravel Eloquent ORM

I can't Insert into this table and this drives me crazy
This is the error Msg I get
var_export does not handle circular references
open: /var/www/frameworks/Scout/vendor/laravel/framework/src/Illuminate/Database/Connection.php
* #param Exception $e
* #param string $query
* #param array $bindings
* #return void
*/
protected function handleQueryException(\Exception $e, $query, $bindings)
{
$bindings = var_export($bindings, true);
$message = $e->getMessage()." (SQL: {$query}) (Bindings: {$bindings})";
Here is my Full Mode
<?php
namespace Models;
use Illuminate\Database\Eloquent\Collection;
class Student extends \Eloquent
{
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'students';
/**
* The rules used to validate new Entry.
*
* #var array
*/
protected $newValidationRules = array(
'studentCode' => 'unique:students,code|numeric|required',
'studentName' => 'required|min:2',
'dateOfBirth' => 'date',
'mobile' => 'numeric'
);
/**
* Relation with sessions (Many To Many Relation)
* We added with Created_at to the Pivot table as it indicates the attendance time
*/
public function sessions()
{
return $this->belongsToMany('Models\Session', 'student_session')->withPivot('created_at')->orderBy('created_at', 'ASC');
}
/**
* Get Student Subjects depending on attendance,
*/
public function subjects()
{
$sessions = $this->sessions()->groupBy('subject_id')->get();
$subjects = new Collection();
foreach ($sessions as $session) {
$subject = $session->subject;
$subject->setRelation('student', $this);
$subjects->add($subject);
}
return $subjects;
}
/**
* Insert New Subject
* #return Boolean
*/
public function insertNew()
{
$this->validator = \Validator::make(\Input::all(), $this->newValidationRules);
if ($this->validator->passes()) {
$this->name = \Input::get('studentName');
$this->code = \Input::get('studentCode');
if ($this->save()) {
return \Response::make("You have registered the subject successfully !");
} else {
return \Response::make('An Error happened ');
}
} else {
Return $this->validator->messages()->first();
}
}
}
I am just trying to insert a new row with three Columns (I call the insertNew function on instance of Student)
1- ID automatically incremented
2- Special Code
3- Name
And I got this above Msg
What's I have tried till now :
removing all relations between from this model and other models
that has this one in the relation
Removed the validation step in insertNew()
Removed the all Input class calls and used literal data instead.
note that I use similar Inserting function on other Models and it works flawlessly
Any Comments , Replies are appreciated :D
Solution
I solved it and the problem was that I am accessing the validator
$this->validator = \Validator::make(\Input::all(), $this->newValidationRules);
And it was because I forgot that
/**
* The validator object.
*
* #var Illuminate\Validation\Validator
*/
protected $validator;
I had a similar problem. But to me, changing this code:
if ($this->validator->passes()) {
$this->name = \Input::get('studentName');
$this->code = \Input::get('studentCode');"
to this:
if ($this->validator->passes()) {
$this->setAttribute ("name" , \Input::get('studentName'));
$this->setAttribute ("code" , \Input::get('studentCode'));"
solved it.

Resources