How to insert into mutiple tables with Laravel - database

I am trying to insert into 2 different tables(House and Contact) using a single method.
public function store(HouseRequest $request){
$dataForm = $request->all();
$house = House::create($dataForm); //Insert into House table
$contact = $house->contact()->create($dataForm['contact']); //Insert into Contact table
return back('dashboard/houses')->with('message', 'Success');
}
Here is my table Contact:
Schema::create('contacts', function (Blueprint $table) {
$table->integer('house_id')->unsigned();
$table->string('name', 255);
$table->char('phone', 11);
$table->timestamps();
$table->foreign('house_id')->references('id')->on('houses')->onDelete('cascade')
}
House Model:
public function contact(){
return $this->hasOne(Contact::class);
}
It works fine (inserts into both tables), but after submitting the form, I got this:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'id' in 'where clause' (SQL: select * from contacts where id = 0 limit 1)
I don't know why it is running the query above. How can I get rid of this error?

You just forgot to add a column for ids add $table->increments('id'); in your migration :
Schema::create('contacts', function (Blueprint $table) {
$table->increments('id');
$table->integer('house_id')->unsigned();
$table->string('name', 255);
$table->char('phone', 11);
$table->timestamps();
$table->foreign('house_id')->references('id')->on('houses')->onDelete('cascade')
}

Related

Inserting date and time as "2021-05-13T12:31" in database?

I am having a datetime input in my form and the user will select date and time from that input. But when inserting, the data should be only date and time, but T also getting inserted? How not to insert it?
Here is the migration code:
public function up()
{
Schema::create('competitions', function (Blueprint $table) {
$table->id();
$table->string('title');
$table->text('desc');
$table->float('entry_fees');
$table->varchar('start_date_time',50);
$table->Date('end_date_time',50);
$table->integer('status');
$table->string('date_time');
$table->timestamps();
});
}
The columns name are start_date_time and end_date_time?
If its just datetime can you not set your columns like this then carbon parse on creating
public function up()
{
Schema::create('competitions', function (Blueprint $table) {
$table->id();
$table->string('title');
$table->text('desc');
$table->float('entry_fees');
$table->datetime('start_date_time');
$table->datetime('end_date_time');
$table->integer('status');
$table->string('date_time');
$table->timestamps();
});
}
first your columns should be dateTime type in your table and then
you can change its format with laravel carbon
$createdAt = Carbon::parse($item['start_date_time']);
Then you can use
$start_date = $createdAt->format('d/m/Y H:i:s');

Foreign key constraint is incorrectly formed - MariaDB & Laravel

I am running a databse migration in laravel 5.8 and I am getting the following error:
Illuminate\Database\QueryException : SQLSTATE[HY000]: General error: 1005 Can't create table cartorque.likes (errno: 150 "Foreign key constraint is incorrectly formed") (SQL: alter table likes add constraint likes_
post_id_foreign foreign key (post_id) references posts (id) on delete cascade on update cascade)
Here are how my tables are setup
User Table:
Schema::create('users', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
Posts Table
Schema::create('posts', function (Blueprint $table) {
$table->bigIncrements('id');
$table->timestamps();
$table->string('title', 500);
$table->longText('content');
$table->tinyInteger('privacy')->default('0');
$table->string('location', 250);
$table->bigInteger('longitude');
$table->bigInteger('latitude');
$table->bigInteger('user_id')->unsigned()->index();
$table->string('slug', 250);
});
Schema::table('posts', function (Blueprint $table) {
$table->foreign('user_id')->references('id')->on('users')
->onDelete('cascade')
->onUpdate('cascade');
});
Likes Table
Schema::create('likes', function (Blueprint $table) {
$table->bigIncrements('id');
$table->timestamps();
$table->unsignedBigInteger('user_id');
$table->unsignedBigInteger('post_id');
$table->boolean('like');
});
Schema::table('likes', function (Blueprint $table) {
$table->foreign('post_id')->references('id')->on('posts')
->onDelete('cascade')
->onUpdate('cascade');
});
Schema::table('likes', function (Blueprint $table) {
$table->foreign('user_id')->references('id')->on('users')
->onDelete('cascade')
->onUpdate('cascade');
});
The Likes table is to have 2 foreign keys user_id and post_id. It works fine on user_id but I get the error on the post_id column
Found the issue and it was the posts table not being created. This happened because the order of the migration files. The likes foreign key creation was occurring prior to the posts table being created. I change the order of the migration files.

Getting value from another table through id

I am new to laravel. I have a table:
students_attendance.
In students_attendance I have a column named class_id, which refers to the students_classes table that also includes the class_id and class_name for each student.
In the frontend table I am getting the values from students_attendance table so the class_id is available, but what I need is the class_name.
How I can get the class_name?
//Migration for students_attendance
public function up()
{
Schema::create('students_attendances', function (Blueprint $table) {
$table->increments('id');
$table->integer('class_id')->index()->unsigned()->nullable();
$table->string('student_id');
$table->string('first_name');
$table->string('last_name');
$table->string('attendance');
$table->timestamps();
});
}
//Migration for students_classes
public function up()
{
Schema::create('students_classes', function (Blueprint $table) {
$table->increments('id');
$table->string('class_name');
$table->string('class_fee');
$table->string('class_teacher');
$table->timestamps();
});
}
//Students Class Model
class StudentsClass extends Model
{
protected $fillable = [
'class_name',
'class_fee',
'class_teacher'
];
public function students() {
return $this->hasMany('App\Students');
}
}
//Students Attendance Model
class StudentsAttendance extends Model
{
protected $fillable = [
'class_id',
'student_id',
'first_name',
'last_name',
'attendance'
];
public function studentsClass() {
return $this->belongsTo('App\StudentsClass');
}
}
From a StatusAttendance variable you can access the class name with $attendance->studentClass->class_name.
Assuming you have the class_id and you want to get the name of the associated class, you can simply do this:
$class = StudentsClass::find($class_id);
$class->class_name; // Outputs the name

Problems with query function laravel

I would like to load the user, which has the appropriate url in the table invites stored. Unfortunately, I do not get the query written. How can I switch to the table "invites" and still load the right user to the page?
Relation:
One to one
Route
Route::get('/invite/{url}', 'Auth\RegisterController#show')->name('invite.show');
Table invites:
Schema::create('invites', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->unsigned()->nullable();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->text('greeting')->nullable();
$table->string('url')->unique();
$table->timestamps();
});
function
public function show($url)
{
$user = User::where(function ($query) use ($url) {
$query->where('invites.url', '=', $url);
})->first();
return view('invite_user', compact('user'));
}
Try this:
$user = User::whereHas('invites', function($query) use($url) {
$query->where('url', $url);
})->first();
Make sure that you have the invites relationship function in your User model like so:
public function invites() {
return $this->hasMany(Invite::class, 'user_id');
}

Laravel return records from relation table

Hello I want to returned a list of products with the selected category.
I have two tables connected by relationship table products:
public function up()
{
Schema::create('products', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->unsigned();
$table->integer('article_id')->unsigned();
$table->integer('category_id')->unsigned();
$table->string('sn');
$table->integer('quantity');
$table->date('warranty');
$table->timestamps();
});
Schema::table('products', function(Blueprint $table) {
$table->foreign('user_id')->references('id')->on('users');
$table->foreign('article_id')->references('id')->on('articles');
$table->foreign('category_id')->references('id')->on('categories');
});
}
and table categories:
public function up()
{
Schema::create('categories', function (Blueprint $table) {
$table->increments('id');
$table->string('category_name');
$table->timestamps();
});
}
product model:
public function user(){
return $this->belongsTo('App\User');
}
public function article(){
return $this->belongsTo('App\Article');
}
public function category(){
return $this->belongsTo('App\Category');
}
And category model:
public function products(){
return $this->hasMany('App\Product')->withTimestamps();
}
I write query SQL in phpmyadmin:
SELECT
products.id,
products.user_id,
articles.article_name,
categories.category_name,
products.sn,
products.quantity,
products.warranty,
products.created_at,
products.updated_at,
SUM(quantity) AS ilosc
FROM
products
LEFT JOIN
categories ON products.category_id = categories.id
LEFT JOIN
articles ON products.article_id = articles.id
GROUP BY articles.article_name
ORDER BY id;
This query works on phpmyadmin but I want write metohod in Laravel. How can I return a list of products assigned to the selected category ?? I would add that the selected category is passed in the method show by ID CATEGORY:
public function show($id){
$categories = Category::find($id);
return view('categories.showcategory', compact('categories'));
}
I do not want a solution, only hints how I can do it. I found this theme enter link description here, but still I do not know how to do it ;)
I convert query SQL to query laravel i file CategoriesController:
public function show($id){
$categories = Category::find($id);
$productsList = DB::table('products')->select('products.id,
products.user_id,
articles.article_name,
categories.category_name,
products.sn,
products.quantity,
products.warranty,
products.created_at,
products.updated_at,
SUM(quantity) AS ilosc')->from('products')->where('id' , '=' , $categories->id)->leftJoin('categories', 'products.category_id', '=', 'categories.id')->leftJoin('articles', 'products.article_id', '=', 'articles.id')->groupBy('articles.article_name')->orderBy('id')->get();
return view('categories.showcategory', compact('categories', 'productsList'));
}
But Laravel returned error:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'products.id, '
in 'field list' (SQL: select products.id, as `` from products
left join categories on products.category_id = categories.id
left join articles on products.article_id = articles.id
where id = 1 group by articles.article_name order by id asc)
with the help of swatkins I wrote method:
public function show($id){
$categories = Category::find($id);
$productsList = Category::with(['products' => function ($query) {
$query->where('category_id', 20);
}])->get();
return view('categories.showcategory', compact('categories', 'productsList'));
}
Laravel returns correctly Products with selected category, but only when I write ID category. In this method ID category is equal to 20.
$query->where('category_id', 20);
How can I dynamically pass the value of GET category_id ??
You already have a category, you just need to eager load the products relationship:
public function show($id){
$categories = Category::with(['products' => function ($query) {
$query->where('paid', true);
}])->find($id);
// this will give you a child property on your category
// called 'products' that will be an array of associated
// Product objects
return view('categories.showcategory', compact('categories'));
}
docs: https://laravel.com/docs/5.2/eloquent-relationships#eager-loading

Resources