insert data into hasone table from a form input in laravel - php

i have two table one is user which is parent and other is posts(child) table and its coulmns are
public function up(){
Schema::create('posts', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id');
$table->string('title');
$table->string('body');
$table->timestamps();
}
}
i have already specified
$this->hasOne('Post');
relation into user model. now i want to insert data into posts table where with form i can save data into title and body column into there respective id's.

If it's an authenticated user, you can do this:
auth()->user()->posts()->create($request->all());
To make create() method work you also need to have $fillable array with all properties in the Post model:
$protected fillable = ['title', 'body'];

Related

How to retrieve specific column value from foreign key table?

There are two Models. One is TradeLicence and another is BusinessCategory.
I have already established relationship between them. In TradeLicence there is a foreign key category_id which local key is id of BusinessCategory.
Trade Licence Model
class TradeLicence extends Model
{
use SoftDeletes;
protected $fillable = ['slug', 'name', 'category_id'];
public function businessCategories()
{
return $this->belongsTo(BusinessCategory::class,'category_id','id');
}
}
trade_licences migration Table:
class CreateTradeLicencesTable extends Migration
{
public function up()
{
Schema::create('trade_licences', function (Blueprint $table) {
$table->id();
$table->string('slug')->unique();
$table->foreignId->('category_id');
$table->string->('name');
$table->timestamps();
});
}
}
Business Category Model:
class BusinessCategory extends Model
{
use SoftDeletes;
protected $fillable = ['slug', 'name', 'fees'];
}
business_categories migration table:
class CreateBusinessCategoriesTable extends Migration
{
public function up()
{
Schema::create('business_categories', function (Blueprint $table) {
$table->id();
$table->string('slug')->unique();
$table->string('name');
$table->double('fees');
$table->timestamps();
});
}
For adding a "Trade Licence", I need to select a "Business Category" and it stores the value
incategory_id column of trade_licencestable. I'm able to retrieve the name and fees value through the relationship inside TradeLicense model.
The problem is:
There is a another Model named DailyEarning. The show() method of DailyEarningController will display fees amount (fee of selected category, which was selected at the time of creating a new trade licence) and created_at and updated_at value of each Trade License.
My Question is:
How to get the values of fees, created_at and updated_at or which Query should I use to retrieve the values by using "Eloquent"?

Laravel save data from one form to different database tables

I want to create a student with some courses.
This is the Laravel view
I created two different tables: a students table
public function up()
{
Schema::create('students', function (Blueprint $table) {
$table->id();
$table->timestamps();
$table->string('student_name');
$table->string('first_name');
$table->string('last_name');
$table->string('email');
});
}
and a courses table.
public function up()
{
Schema::create('student_courses', function (Blueprint $table) {
$table->id();
$table->unsignedInteger('student_id');
$table->string('course_name');
$table->timestamps();
});
}
The students table creates the information of the student and saves it in the student table.
I want to save the courses into the courses table, with the student id. They should have a One to Many relationship. How can I save the different courses into the courses table with the id of the specific student?
You can't store course name in student courses table. You need to create separate tables for courses. After that you can use foreign key for store both the data of student and courses into the student_courses table as per below.
public function up()
{
Schema::create('student_courses', function (Blueprint $table) {
$table->id();
$table->integer('student_id')->unsigned()->nullable();
$table->foreign('student_id')->references('id')->on('students')->onDelete('cascade');
$table->integer('course_id')->unsigned()->nullable();
$table->foreign('course_id')->references('id')->on('courses')->onDelete('cascade');
$table->timestamps();
});
}
Hope this will helps you.
First create Relationship:
In User Model Create:
public function courses(){
return $this->hasMany(Course::class);
}
In Course Model Create:
public function students(){
return $this->belongsTo(Studnet::class);
}
Now in your save function:
$course = new Course($request->all());
$user->courses()->save($course);

Laravel - A show can have multiple providers

So I am trying to figure a solution to this but not sure exactly how to do this. I have a table that stores all the shows that happen. In a given show I can have multiple providers attend that show. A provider could also attend many shows as well. So how do I store this in the DB and do the eloquent relationship?
Show Schema
Schema::create('shows', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->integer('number')->unsigned();
$table->dateTime('airDate');
$table->string('podcastUrl')->nullable();
$table->timestamps();
});
Provider Schema
Schema::create('providers', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('shortName')->nullable();
$table->string('image')->nullable();
$table->string('social')->nullable();
$table->timestamps();
});
Would I store the provider_id in the shows schema?
Update 1
So I created a new migration for a pivot table
Schema::create('provider_show', function (Blueprint $table) {
$table->integer('provider_id')->unsigned()->index();
$table->foreign('provider_id')->references('id')->on('providers')->onDelete('cascade');
$table->integer('show_id')->unsigned()->index();
$table->foreign('show_id')->references('id')->on('shows')->onDelete('cascade');
$table->primary(['provider_id', 'show_id']);
});
Then in the show model I created the following
public function providers()
{
return $this->belongsToMany(Provider::class);
}
Now when I am saving a new show I added a multiselect to select the providers I want
$show = new Show;
$show->name = $request->name;
$show->number = $request->number;
$show->airDate = $request->airDate;
$show->podcastUrl = $request->podcastUrl;
$show->providers()->attach($request->providerList);
$show->save();
Session::flash('message', "Created Successfully!");
return back();
Then when I save I get the following error
SQLSTATE[23000]: Integrity constraint violation: 19 NOT NULL constraint failed: provider_show.show_id (SQL: insert into "provider_show" ("provider_id", "show_id") select 1 as "provider_id", as "show_id" union all select 2 as "provider_id", as "show_id")
Create a provider_show migration which will act as your pivot table.
This table would contain both provider_id and show_id which will provide the many-to-many relationship between those entities.
Then on your Provider model you can provide a shows() method which returns a BelongsToMany relationship.
// In your Provider model
public function shows()
{
return $this->belongsToMany('App\Show');
}
Note that Laravel by default looks for a pivot table name based alphabetically on the two relationships.
You can also add the inverse on your Show model by providing a providers() method that also returns a BelongsToMany relationship.

laravel making categories for a post (normalizing table)

Laravel normalizing relationship in DB.
So I've jobs table that contains job. And categories table that contains category.
job can have multiple categories.
Is there a laravely way of normalizing the relationship?
Schema::create('jobs', function($table)
{
$table->increments('id');
$table->integer('user_id')->unsigned();
$table->string('slug');
$table->string('title');
$table->string('excerpt')->nullable();
$table->text('content');
$table->integer('delivery');
$table->integer('price');
$table->unique(array('user_id', 'slug'));
$table->timestamps();
});
Schema::create('categories', function(Blueprint $table)
{
// These columns are needed for Baum's Nested Set implementation to work.
// Column names may be changed, but they *must* all exist and be modified
// in the model.
// Take a look at the model scaffold comments for details.
// We add indexes on parent_id, lft, rgt columns by default.
$table->increments('id');
$table->integer('parent_id')->nullable()->index();
$table->integer('lft')->nullable()->index();
$table->integer('rgt')->nullable()->index();
$table->integer('depth')->nullable();
// Add additional columns here (f.ex: name, slug, path, etc.)
$table->string('name')->unique();
$table->string('slug')->unique();
$table->string('description')->nullable();
});
My first instinct is to create an intermediary table that holds relationship:
Schema::create('jobs_categories', function($table)
{
$table->increments('id');
$table->integer('job_id')->unsigned();
$table->integer('category_id')->unsigned();
$table->unique(array('job_id', 'category_id'));
});
But I'm not sure how to proceede, what would I do if I want to get categories along with all $jobs?
What do I do if I want to get $job category?
Is hasOne, hasMany a better suited for this?
What you're describing is a many-to-many relationship. And yes, a pivot table like jobs_categories is needed. Here's how you do it following Laravels naming convention and making use of relationships:
Pivot table
jobs_categories is fine but Laravel likes category_job (singular and alphabetical order) (This way you don't have to specify the table name in your relation)
Schema::create('category_job', function($table){
$table->increments('id');
$table->integer('job_id')->unsigned();
$table->integer('category_id')->unsigned();
$table->unique(array('job_id', 'category_id'));
// foreign key constraints are optional (but pretty useful, especially with cascade delete
$table->foreign('job_id')->references('id')->on('jobs')->onDelete('cascade');
$table->foreign('category_id')->references('id')->on('categories')->onDelete('cascade');
});
Relationships
Job model
public function categories(){
return $this->belongsToMany('Category');
}
Category model
public function jobs(){
return $this->belongsToMany('Job');
}
Usage
Jobs with categories eager loaded
$jobs = Job::with('categories')->get();
Access categories of a job
$job = Job::find(1);
$categories = $job->categories;
Visit the Laravel docs for more information on Eloquent relationships

What type of relationship these two tables will have in laravel?

i have four tables in database:
users (for storing user details)
conversations (for storing conversations id).
conversationsmember (for storing conversations member)
conversationsreply (for storing conversations reply)
A user will have many conversations and each conversation will have its members and replies.
here are the details:
Users migration:
$table->increments('id');
$table->string('name', 32);
$table->string('username', 32);
$table->string('email', 320);
$table->string('password', 64);
$table->timestamps();
Conversations migration:
$table->increments('id');
$table->timestamps();
conversationsmembers migration:
$table->increments('id');
$table->integer('conversation_id');
$table->integer('user_id');
$table->timestamps();
conversationsreply migrations
$table->increments('id');
$table->integer('conversation_id');
$table->integer('user_id');
$table->timestamps();
Now in User model, i need to define relationship between users table and conversations table. As they are not directly connected, i used hasManyThrough relation.
..app/models/User.php
...
public function conversations()
{
return $this->hasManyThrough('Conversation', 'ConversationsMember', 'conversation_id', 'id');
}
...
When i 'm trying to use it, it's showing a blank array.
I would try a belongsToMany relationship, where conversationsmembers is your pivot table.
public function conversations()
{
return $this->belongsToMany('Conversation', 'conversationsmembers');
}
You may also want to define the inverse of the relationship in your Conversation model:
public function users()
{
return $this->belongsToMany('User', 'conversationsmembers');
}
I'm a bit confuse about your migration so I'm not sure that's what you want.

Categories