Trying to get the relation using laravel eloquent but get null - laravel-5

I have two table with the following fields
adviser_group
`id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
`user_id` INT(10) UNSIGNED NOT NULL,
`organization_id` INT(10) UNSIGNED NOT NULL,
organizations
`id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
`name` VARCHAR(191) NOT NULL COLLATE 'utf8mb4_unicode_ci',
`status` TINYINT(4) NOT NULL DEFAULT '0',
adviser_group has 1 row,
organization has many row
Using laravel uloquent i'm trying this,
$organization = OrganizationAdviserGroup::with('organization')
->where('user_id', '=', Auth::user()->id)
->get();
But what I get, is the organization = null
Am i doing it wrong?

if you are using laravel just look at this docs, it's realy simple and easy to understand
Eloquent Relationships

Related

Need help in Laravel Eloquent for Multiple Join

I have 3 tables. Events, Events_join , Customers . in event_join I have only customer id those who join the event. currently, I fetching events with an array of events_join using this
my DB structure is:
Table structure for table my_events
CREATE TABLE IF NOT EXISTS `my_events` (
`id` int(10) unsigned NOT NULL,
`userid` int(11) NOT NULL,
`title` varchar(255) COLLATE utf8_unicode_ci NOT NULL DEFAULT '',
`sdes` varchar(256) COLLATE utf8_unicode_ci NOT NULL DEFAULT '',
`pic` varchar(100) COLLATE utf8_unicode_ci NOT NULL DEFAULT '1',
`sdate` date NOT NULL DEFAULT '1970-01-01',
`edate` date NOT NULL DEFAULT '1970-01-01',
`country` int(11) NOT NULL,
`city` int(11) NOT NULL,
`location` varchar(256) COLLATE utf8_unicode_ci NOT NULL,
`url` varchar(256) COLLATE utf8_unicode_ci NOT NULL,
`des` varchar(10000) COLLATE utf8_unicode_ci NOT NULL DEFAULT '',
`cat` int(10) unsigned NOT NULL DEFAULT '1',
`deleted_at` timestamp NULL DEFAULT NULL,
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL,
`timezone` varchar(90) COLLATE utf8_unicode_ci NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
Table structure for table customers
CREATE TABLE IF NOT EXISTS `customers` (
`id` int(10) unsigned NOT NULL,
`title` varchar(10) COLLATE utf8_unicode_ci NOT NULL,
`firstname` varchar(50) COLLATE utf8_unicode_ci NOT NULL DEFAULT '',
`lastname` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
`username` varchar(100) COLLATE utf8_unicode_ci NOT NULL DEFAULT '',
`email` varchar(255) COLLATE utf8_unicode_ci NOT NULL DEFAULT '',
`phone` varchar(40) COLLATE utf8_unicode_ci NOT NULL,
`country` int(10) unsigned NOT NULL DEFAULT '1',
`city` int(10) DEFAULT NULL,
`company` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`password` varchar(255) COLLATE utf8_unicode_ci NOT NULL DEFAULT '',
`pic` varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL,
`level` int(10) unsigned NOT NULL DEFAULT '1',
`status` tinyint(4) NOT NULL DEFAULT '1',
`deleted_at` timestamp NULL DEFAULT NULL,
`created_at` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
`updated_at` timestamp NULL DEFAULT NULL
) ENGINE=InnoDB AUTO_INCREMENT=19 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
Table structure for table events_join
CREATE TABLE IF NOT EXISTS `events_join` (
`id` int(11) NOT NULL,
`userid` int(11) NOT NULL,
`eventid` int(11) NOT NULL,
`sdate` date NOT NULL,
`edate` date NOT NULL,
`date` datetime NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
My Events model have this
public function customers()
{
return $this->belongsToMany(Events::class,EventsJoin::class);
}
My Customer model have this
public function events()
{
return $this->belongsToMany(Customer::class,EventsJoin::class);
}
My EventsJoin have this Pivot
public function customer()
{
return $this->belongsTo(Customer::class);
}
public function event()
{
return $this->belongsTo(Events::class);
}
my eventControler have this
$events=Customer::with(['event']);
but its return empty record. the way its working is customers can create events and other customers will join the event. currently those join the events save with userid in events_join table. I want to join events_join table with the customers table so that I can get additional information of the customer.
While not mentioned in your code, I would have to guess that you have 3 Models, one Events, another one for EventsJoin and one for Customers.
What you seem to have, although you don't say it, is a Many to Many relationship in which a Customer can be in Multiple Events and an Event can be joined by Multiple customers.
In Laravel eloquent terms a Many for Many relationship is described with a belongsToMany.
Take a look at the documentation: https://laravel.com/docs/master/eloquent-relationships#many-to-many
Because it is a Many to Many relationship, the EventsJoin needs to extend Pivot and not Model.
So you would have in your Customer Model something like:
public function events()
{
return $this->belongsToMany(Customer::class,EventsJoin::class);
}
And in your EventsJoin Pivot model
public function customer()
{
return $this->belongsTo(Customer::class);
}
public function event()
{
return $this->belongsTo(Event::class);
}
And in your Events Model
public function customers()
{
return $this->belongsToMany(Event::class,EventsJoin::class);
}
When you wish to get the array of event objects you would do $customer->events;
And when you wish to get the array of customers from the event you would do $event->customers;
Do note that plural and singular cases are important for Laravel Eloquent.

PHP function stripos() expects parameter 1 to be string, object given

I'm running through Laravel 6.0's addSelect() method as the official documentation described. However, I'm getting an error as my title suggested.
Two corresponding tables are:
CREATE TABLE `destinations` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(90) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=latin1
CREATE TABLE `flights` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(90) NOT NULL,
`destination_id` int(11) NOT NULL,
`arrived_at` datetime NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=latin1
The corresponding controller:
use App\Flight;
use App\Destination;
class TestController extends Controller
{
public function Index()
{
return Destination::addSelect(['last_flight' =>
Flight::select('name')
->whereColumn('destination_id', 'destinations.id')
->orderBy('arrived_at', 'desc')
->limit(1)
])->get();
}
}
What is the object provided as a parameter, which is responsible for the error?

Laravel many migrations issue

10 people start new project with laravel.
After for example 2,3 years there will be many migrations.
In case when new programmer joins the team he will setup development environment with code and database.
The problem is that if there are many migrations it will run too slow if there are thousand of migrations.
How to handle this?
Yes running 100s of migrations each time is going to become a headache. You'll want to create a snapshot of your database tables and make that your first migration.
For example lets say you have a blog with a posts and users table. For each table you're going to need a create table statement. If you're working with MySql to get your create table statement for your users table you would query:
SHOW CREATE TABLE users
Once you have your create table statements you can make a new migration which runs those queries and archive all your old migrations.
class CreateSnapshotTables extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
// Create users table
DB::statement("
CREATE TABLE `users` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`password` varchar(60) COLLATE utf8_unicode_ci NOT NULL,
`email` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`name` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`remember_token` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL,
`deleted_at` timestamp NULL DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `users_email_unique` (`email`)
);
");
// Create posts table
DB::statement("
CREATE TABLE `posts` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`title` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
// ...etc.
PRIMARY KEY (`id`),
UNIQUE KEY `users_email_unique` (`email`)
);
");
}
}

Laravel Models Poperty of non-object

I have a People table
CREATE TABLE `people` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`job_title` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`profile_pic` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL,
`departments` varchar(500) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=95 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
An a departments table
CREATE TABLE `departments` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`people_id` int(11) NOT NULL,
`department_id` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=50 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
One person can be in many departments
In the departments table the foreign_key is people_id
In my people model
public function departments()
{
return $this->hasMany('App\Models\Departments', 'id', 'people_id');
}
and finally I try and return some results
return $people::find(1)->departments;
I get the error,
**ErrorException in web.php line 129:
Trying to get property of non-object**
Forgive me if this is a stupid error, I have used laravel for a while but never set up models with relationships before.
Try this Piece of code:-
Get All records
$people = People::with('departments')->get();
$people = json_decode(json_encode($people),true) //Convert in to array
echo "<pre>"; print_r($people); die; //print it
Get 1 record
$people = People::with('departments')->first();
$people = json_decode(json_encode($people),true) //Convert in to array
echo "<pre>"; print_r($people); die; //print it
Hope it helps!
So in the end it was a stupid issue.
$people::find(1)->departments;
Find takes an id but the id of 1 did not exist.

How to save INT fields as null in laravel

I'm getting an error when saving some empty text, textarea fields. Laravel forms this sql query:
SQLSTATE[HY000]: General error: 1366 Incorrect integer value: '' for column 'inside_area' at row 1 (SQL: insert into `ads` (`street`, `quarter`, `building_number`, `inside_area`, `price`, `admin_comment`, `valid_to`, `price_heating`, `rooms`, `floor_number`, `floors_number`, `kitchen_area`, `years`, `public_comment`, `video_url`, `3d_url`, `user_id`, `updated_at`, `created_at`) values (, , , , , , , , , , , , , , , , 1, 2017-03-13 14:33:50, 2017-03-13 14:33:50))
P.S. db table was created not in laravel way - I'm using existing tables, this may be important.
UPDATED: problem are only with INT fields, if they has empty form field on saving!
Table:
CREATE TABLE `ads` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`user_id` int(11) DEFAULT NULL,
`ad_type_id` int(11) DEFAULT NULL,
`city_id` int(11) DEFAULT NULL,
`street` varchar(255) DEFAULT NULL,
`quarter` varchar(255) DEFAULT NULL,
`building_number` varchar(255) DEFAULT NULL,
`inside_area` int(11) DEFAULT NULL,
`price` int(11) DEFAULT NULL,
`show_price_per_meter` int(1) DEFAULT NULL,
`price_heating` int(10) DEFAULT NULL,
`admin_comment` text,
`valid_to` datetime DEFAULT NULL,
`rooms` int(11) DEFAULT NULL,
`floor_number` int(11) DEFAULT NULL,
`floors_number` int(11) DEFAULT NULL,
`kitchen_area` int(11) DEFAULT NULL,
`balcony` int(1) DEFAULT NULL,
`balcony_glazed` int(1) DEFAULT NULL,
`years` int(11) DEFAULT NULL,
`dyn_house_type_id` int(11) DEFAULT NULL,
`dyn_heating_id` int(11) DEFAULT NULL,
`dyn_installation_ids` int(11) DEFAULT NULL,
`public_comment` text,
`video_url` varchar(11) DEFAULT NULL,
`3d_url` varchar(11) DEFAULT NULL,
`available_for_trade` int(1) DEFAULT NULL,
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
FORM:
{!! Form::open(['url'=>'ads']) !!}
{!! Form::number('inside_area', null, ['class'=>'form-control']) !!}
{!! Form::close() !!}
Route:
Route::resource('ads', 'AdsController');
Save action:
public function store() {
$input = Request::all();
\App\Ad::create($input);
return redirect('/ads/my_index');
}
P.S.2 If I provide any value to inside_area field, it goes ok and the next error is for price field.
You can use attribute mutator for each integer attribute. In these mutators you can prepare data before inserting into DB.
In your case you should create mutators in your model Ads for every field with the type INT:
// define a mutator for the field "inside_area"
public function setInsideAreaAttribute($value)
{
$this->attributes['inside_area'] = (int) $value;
}
I understand that creating such a mutator for each INT field is boring, but it will also grant you ability to control user input before inserting into DB.
You can find more information about mutators here (for the latest version of Laravel at this moment):
Laravel 5.4, Defining a Mutator:
https://laravel.com/docs/5.4/eloquent-mutators#defining-a-mutator
Perhaps, you are passing string data to 'inside_area' variable. Because there is more default null fields at your table, like 'city_id', 'ad_type_id'
another way is to use Iatstuti and provide in Ad.php model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Iatstuti\Database\Support\NullableFields;
class Ad extends Model {
use NullableFields;
public $timestamps = true;
protected $nullable = [
'inside_area'
];
protected $fillable = [
'user_id',
'ad_type_id',
'inside_area'
];
}

Resources