I need some help with this...I'm making a function for tags with a tutorial, but in my database ( post_tag ), my post_id isn't saved, only tag_id and id.In my posts table, after create a post I receive the id of post, but here, in my post_tag isn't.Do you know why guys...?
My controller
public function create(){
$tags = Tag::all();
return view('posts.create')->withTags($tags);
}
public function store(Request $request )
{
$data = request()->validate([
'caption' => 'required|max:255',
'image' => 'required|image',
]);
$post = new Post;
$post->tags()->sync($request->tags, false);
$imagePath = request('image')->store('uploads', 'public');
$image = Image::make(public_path("storage/{$imagePath}"))->fit(1600, 1100);
$image->save();
auth()->user()->posts()->create([
'caption' => $data['caption'],
'image' => $imagePath,
]);
return redirect('/profile/' . auth()->user()->id);
}
My create_post_tag_table
public function up()
{
Schema::create('post_tag', function (Blueprint $table) {
$table->bigIncrements('id');
$table->integer('post_id')->unsigned();
$table->foreign('post_id')->references('id')->on('posts');
$table->integer('tag_id')->unsigned();
$table->foreign('tag_id')->references('id')->on('tags');
});
}
My create_posts_table
public function up()
{
Schema::create('posts', function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedBigInteger('user_id');
$table->string('caption');
$table->string('image');
$table->timestamps();
$table->index('user_id');
});
}
You have created a new Post object, but you have not saved it yet in this line:
$post = new Post;
Thus, in this line, immediately following:
$post->tags()->sync($request->tags, false);
There is no id in the database for this post as yet (nor will there be an id on the Post model), and thus sync will fail every time because it can't find the id.
After you new up the Post object, save() it and then you can sync.
On a different note that may help in other ways, your post model has a big int as its id:
Schema::create('posts', function (Blueprint $table) {
$table->bigIncrements('id');
}
But your post_tag table is only an integer. This mismatch may cause some issues. Suggest changing to match:
Schema::create('post_tag', function (Blueprint $table) {
$table->bigIncrements('id');
$table->integer('post_id')->unsigned(); // <--- suggest change this to bigInteger
$table->foreign('post_id')->references('id')->on('posts');
I may be wrong, but since you don't have the onUpdate or onDelete properties in your table associated with your foreign keys, it could be the problem.
The correct solution was this:
$post = auth()->user()->posts()->create([
'caption' => $data['caption'],
'image' => $imagePath,
]);
I just added this to my code, and all was ok.
Related
This is my original table called questions:
public function up()
{
Schema::create('questions', function (Blueprint $table) {
$table->id();
$table->string('title');
$table->string('slug');
$table->string('image')->nullable();
$table->string('audio')->nullable();
$table->string('type');
$table->unsignedBigInteger('evaluation_id');
$table->foreign('evaluation_id')->references('id')->on('evaluations')->onDelete('cascade');
$table->timestamps();
});
}
And with this code, I added a new column to the existing table:
php artisan make:migration add_rule_to_questions_table --table=questions
php artisan migrate
In the migration file of the new column added this in up() method:
public function up()
{
Schema::table('questions', function (Blueprint $table) {
$table->longText('rule')->nullable();
});
}
At this point, the new column added succesfully to the database. But, when I try to add data to the new column of the "questions" table, data is not saved in the database.
In create form I use this code:
<div class="form-group">
<label>Rules:</label>
<textarea name="rule" id="rule" class="form-control" value="{{old('rule')}}"></textarea>
#error('rule')
<small class="text-danger">{{$message}}</small>
#enderror
</div>
Finally in store method() of controller I save data with this code:
public function store(Request $request){
Question::create([
'title' => $request->title,
'slug' => $request->slug,
'evaluation_id' => $request->evaluation_id,
'type' => "OM",
'rules' => $request->rule,
]);
}
But the new column is not saving data, what could be the error?
You need add rules to array $fillable in your Question model
I am creating factories and saving the page model to the film model so its film to page one-to-many,
i've followed the docs but when im trying to save the models to each other i am getting this error
General error: 20 datatype mismatch (SQL: insert into "pages" ("id", "page_url", "film_id", "updated_at", "created_at") values (591d61cb-3090-3945-b920-ba797245cb97, http://larson.com/, bd3bab38-f8be-4674-ae5d-15e8f6b6172a, 2019-11-15 11:23:02, 2019-11-15 11:23:02))
These are the classes i am working with
Film migration
public function up()
{
Schema::create('films', function (Blueprint $table) {
$table->uuid('id')->primary();
$table->string('name');
$table->string('description');
$table->timestamps();
});
}
Pages migration
public function up()
{
Schema::create('pages', function (Blueprint $table) {
$table->bigIncrements('id');
$table->uuid('film_id')->nullable();
$table->string('page_url')->nullable();
$table->timestamps();
});
}
PagesFactory
$factory->define(Pages::class, function (Faker $faker) {
return [
'id' => $faker->uuid,
'page_url' => $faker->url,
'film_id' => factory(\App\Models\Film::class)->create()->id
];
Pages model
public function film(): BelongsTo
{
return $this->belongsTo(Film::class);
}
FilmController
*/
public function show(string $id)
{
$film = Film::with([
'pages',
'languages',
'categories',
])->findOrFail($id);
return $film;
FilmControllerTest
public function getFilmTest()
{
$film = factory(Film::class)->create();
$language = Language::where('id', 'en')->where('name', 'English')->first();
$categories = Category::where('main-cat', 'Science')->where('sub-cat', 'Fiction')->first();
$film->pages()->save(factory(Page::class)->create());
$film->languages()->attach($language->id);
$film->categories()->attach($categories->id);
$response = $this->json('GET', '/film/' . $film->id)
->assertStatus(200);
$response
->assertJson(['id' => $guestProfile->id])
->assertJson(['name' => $film->description])
->assertJson(['languages' => $film->languages->toArray()])
->assertJson(['categories' => $film->categories->toArray()])
}
when i comment out this line from the test it works fine $film->pages()->save(factory(Page::class)->create());
im abit lost on why im having this issue trying to save the models so the pages becomes part of the response... can i get some help/example please :D
The id of your pages table is set to a bigIncrements (UNSIGNED BIGINT), but in your PagesFactory you are trying to store a uuid.
$factory->define(Pages::class, function (Faker $faker) {
return [
'id' => $faker->uuid,
'page_url' => $faker->url,
'film_id' => factory(\App\Models\Film::class)->create()->id
];
Remove 'id' => $faker->uuid, from the factory, you don't have to set an auto incrementing field.
Another option (depending on the design you have in mind) is to change the migration of the pages table and set the id column to $table->uuid('id')->primary();
try using the make() method, as in:
$film->pages()->save(factory(Page::class)->make());
I am new in LARAVEL and i got some issues.
My problem is that when i insert data into the first table i can see that it has an id settled by default but when i insert data into the second table i keep getting this error :
SQLSTATE[HY000]: General error: 1364 Field 'etudiant_id' doesn't have
a default value
What should i do to give the foreign key the id number of the first table?
Here is my Schemas :
the first table -etudiant- :
public function up()
{
Schema::create('etudiants', function (Blueprint $table) {
$table->increments('id');
$table->string('nom');
$table->timestamps();
});
}
the second table -bac2- :
public function up()
{
Schema::create('bac2', function (Blueprint $table) {
$table->increments('id');
$table->integer('etudiant_id')->unsigned();
$table->foreign('etudiant_id')->references('id')->on('etudiants')-
>onDelete('cascade') ;
$table->date('anne_bac2');
$table->timestamps();
});
}
Here is my insertion function :
function insert(Request $req){
$nom = $req->input('name');
$data= array('nom'=>$nom);
$anne_bac2 = $req->input('anne_bac2');
$data2= array('anne_bac2'=>$anne_bac2);
DB::table('etudiants')->insert($data);
DB::table('bac2')->insert($data2);
return "success";
}
You need to add foreign key to the data you're trying to insert. So, change these lines:
$data2= array('anne_bac2'=>$anne_bac2);
DB::table('etudiants')->insert($data);
DB::table('bac2')->insert($data2);
To:
$etudiantId = DB::table('etudiants')->insertGetId($data);
$data2 = ['anne_bac2' => $anne_bac2, 'etudiant_id' => $etudiantId];
DB::table('bac2')->insert($data2);
Or better refactor whole method:
function insert(Request $request)
{
$etudiantId = DB::table('etudiants')->insertGetId(['nom' => $request->name]);
DB::table('bac2')->insert(['anne_bac2' => $request->anne_bac2, 'etudiant_id' => $etudiantId]);
return "success";
}
I can get the current user that logged in. But I don't know how can I passed this into variable. I can the user id by this.
public function getDocuments()
{
//GETTING ALL THE ID OF THE USERS IN THE DATABASE EXCEPT THE ID OF CURRENT USER.
$resultRecipient = DB::table('users')->where('id', '!=', Auth::id())->get();
//GETTING ALL THE CATEGORIES.
$resultCategory = DB::table('categories')->get();
//VIEW
return view ('document.create')->with('resultRecipient', $resultRecipient)->with('resultCategory', $resultCategory);
if(\Auth::user()->id)
{
echo "You get the id";
}
else
{
echo "Failed";
}
}
Can anyone tell me how can I sync the current user id when the submit button is submitted. Is there a way how can I attach the id of the user in the sync method?
public function postDocuments(Request $request)
{
$this->validate($request,
[
'title' => 'required|alpha_dash|max:255',
'content' => 'required',
'category_id' => 'required',
'recipient_id' => 'required',
]);
$document = new Document();
//Request in the form
$document->title = $request->title;
$document->content = $request->content;
$document->category_id = $request->category_id;
$document->save();
$document->recipients()->sync($request->recipient_id, false);
return redirect()->back();
}
UPDATE!
According to #Ariful. I can add the instance of Auth::user(); to get the id. But it doesn't return me the id to my pivot table and gives me a error.
SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (webdev.document_user, CONSTRAINT document_user_user_id_foreign FOREIGN KEY (user_id) REFERENCES users (id) ON DELETE CASCADE) (SQL: insert into document_user (document_id, user_id) values (59, 0))
public function postDocuments(Request $request)
{
$this->validate($request,
[
'title' => 'required|alpha_dash|max:255',
'content' => 'required',
'category_id' => 'required',
'recipient_id' => 'required',
]);
$user = Auth::user();
$document = new Document();
//Request in the form
$document->title = $request->title;
$document->content = $request->content;
$document->category_id = $request->category_id;
$document->save();
$document->recipients()->sync([$request->recipient_id, $user->id, false]);
return redirect()->back();
}
Models:
User Model
class User extends Model implements AuthenticatableContract
{
public function documents()
{
return $this->belongsToMany('App\Models\Document', 'document_user', 'user_id', 'document_id');
}
}
Document Model:
class Document extends Model
{
public function recipients()
{
return $this->belongsToMany('App\Models\User', 'document_user', 'document_id', 'user_id');
}
}
Migration:
User migration
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('first_name');
$table->string('last_name');
$table->string('middle_name');
$table->string('email');
$table->string('username');
$table->string('address');
$table->string('password');
});
}
Documents migration:
public function up()
{
Schema::create('documents', function (Blueprint $table) {
$table->increments('id');
$table->string('title');
$table->text('content');
$table->integer('category_id')->unsigned();
$table->foreign('category_id')->references('id')->on('categories')->onDelete('cascade');
$table->timestamps();
});
}
documents_user migration:
public function up()
{
Schema::create('document_user',function (Blueprint $table)
{
$table->increments('id');
$table->integer('user_id')->unsigned();
$table->integer('document_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->foreign('document_id')->references('id')->on('documents')->onDelete('cascade');
$table->unsignedInteger('sender_id')->nullable();
$table->foreign('sender_id')->references('id')->on('users')->onDelete('cascade');
$table->dateTime('dateReceived')->default(DB::raw('CURRENT_TIMESTAMP'));
});
}
Screenshot Database:
UPDATE 2:
I can insert a values on my user_id based on the user's choice in the select list.
This is where the values of the form inserted in the user_id column. I just need to insert the current user in my sender_id so I can determined who send the data.
<div class = "form-group">
<label for = "recipient_id" class = "control-label">To:</label>
<select name = "recipient_id[]" multiple class = "form-control" id = "myUserList">
#foreach ($resultRecipient as $list)
<option value = "{{ $list->id }}">{{ $list->username }}</option>
#endforeach
</select>
</div>
As you can see here I just insert this manually based on the users table data. Still don't have idea how can I insert the current user into sender_id column.
I believe this should work
$user = Auth::user(); //get current user
$document->recipients()->sync([$user->id]);
UPDATED Source Link
$document->recipients()->sync( [ $request->recipient_id, $user->id ], false );
As per documentation,
The sync method accepts an array of IDs to place on the intermediate table.
UPDATE 2
$document->recipients()->sync( [ $request->recipient_id =>
['sender_id' => $user->id] ],
false );
Your sender_id is not part of your relationship. So you need to add it as extra info.
UPDATE 3
After discussion, this should be your main code
foreach($request->recipient_id as $receipentId){
$document->recipients()->sync( [ $receipentId =>
['sender_id' => $user->id] ],
false );
}
This will loop through your receipent_id array and take each id for sync with the current logged in user as $user->id;
I have created two tables in laravel 5.2 one is called "users" and the other is called "artists_details" and they have a one to one relationship. the schema of the users table is as follows
Schema::create('users', function (Blueprint $table) {
$table->engine = 'InnoDB';
$table->increments('id');
$table->boolean('admin')->nullable();
$table->boolean('manager')->nullable();
$table->string('name');
$table->string('email')->unique();
$table->string('password', 60);
$table->rememberToken();
$table->timestamps();
});
and the schema of the artists table is as follows
Schema::create('artists_details', function (Blueprint $table) {
$table->engine = 'InnoDB';
$table->integer('user_id')->unsigned();
$table->string('artists_image_path');
$table->string('name');
$table->integer('phone_no');
$table->integer('passport');
$table->string('city');
$table->string('county');
$table->string('facebook_name');
$table->string('twitter_handle');
$table->string('email');
$table->string('alternative_email');
$table->string('website');
$table->text('biography');
$table->timestamps();
$table->foreign('user_id')
->references('id')
->on('users')
->onDelete('CASCADE');
});
I have indicated the relationship in the models as follows
User model
public function artists_relation()
{
return $this->hasOne('App\artists_details_model');
}
and on the artists_details_model as follows
public function user_artist_details()
{
return $this->belongsTo('App\User');
}
The php code that handles the form submission in the controller is as follows
public function artists_details_store(Request $request)
{
$input = \Request::all();
$file = $request->file('file');
$name = time(). $file->getClientOriginalName();
$file->move('artists_image/photo', $name);
$artists_input = new artists_details_model;
$artists_input->artists_image_path = 'artists_image/photo/'. $name;
$artists_input->name = $input['name'];
$artists_input->phone_no = $input['phone_no'];
$artists_input->passport = $input['passport'];
$artists_input->city = $input['city'];
$artists_input->county = $input['county'];
$artists_input->facebook_name = $input['facebook_name'];
$artists_input->twitter_handle = $input['twitter_handle'];
$artists_input->email = $input['email'];
$artists_input->alternative_email = $input['alternative_email'];
$artists_input->website = $input['website'];
$artists_input->biography = $input['biography'];
$artists_input->save();
return redirect('create');
}
When i click on the submit button i get the following error message
QueryException in Connection.php line 669:
SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or
update a child row: a foreign key constraint fails
I cant seem to see where i am going wrong or what seems to be the problem
For the table 'artists_details' you have mentioned as
$table->foreign('user_id')
->references('id')
->on('users')
So whenever you try to save the details in the 'artists_details' you need to provide the 'user_id' without which the information will not get saved.
Either you need to pass the 'UserID' as a hidden parameter or if the UserID is saved in the Session, then you need to retrieve it from the Session.
You do not seem to be including the foreign key {user_id} on your form