I am trying to save boolean value when I create a new Post and then have it update the value if I update the Post. When I create a new Post and save, it persists to the database and I can even update it without issue. I am just having a little trouble dealing with a checkbox boolean. This is my fist project in Laravel, which is part of my hurdle I'm sure.
schema
...
public function up()
{
Schema::create('posts', function (Blueprint $table) {
$table->increments('id');
$table->unsignedBigInteger('user_id');
$table->string('title');
$table->text('body')->nullable();
$table->string('photo')->nullable();
$table->boolean('is_featured')->nullable()->default(false);
$table->boolean('is_place')->nullable()->default(false);
$table->string('tag')->nullable()->default(false);
$table->timestamps();
});
Schema::table('posts', function (Blueprint $table) {
$table->foreign('user_id')->references('id')->on('users');
});
}
...
PostController.php
...
public function store(Request $request)
{
$rules = [
'title' => ['required', 'min:3'],
'body' => ['required', 'min:5']
];
$request->validate($rules);
$user_id = Auth::id();
$post = new Post();
$post->user_id = $user_id;
$post->is_featured = request('is_featured');
$post->title = request('title');
$post->body = request('body');
$post->save();
$posts = Post::all();
return view('backend.auth.post.index', compact('posts'));
}
...
post/create.blade.php
...
<input type="checkbox" name="is_featured" class="switch-input"
value="{{old('is_featured')}}">
...
If I'm understanding the problem correctly, you can cast the attribute as a boolean in the model.
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
protected $casts = [
'is_featured' => 'boolean',
'is_place' => 'boolean',
];
}
Then in your form you'll want to check that value to determine if the box is checked.
<input type="checkbox" name="is_featured" class="switch-input" value="1" {{ old('is_featured') ? 'checked="checked"' : '' }}/>
In your controller, you'll want to just check if the input is submitted. An unchecked input won't be sumitted at all.
$post->is_featured = $request->has('is_featured');
try this
$post->is_featured = $request->input('is_featured') ? true : false;
Related
I have two models Batch and Notices. The foreign key is correctly formed and data is saved in the database. Now I can't show the data on my listing blade.
Notice Migration:
Schema::create('notices', function (Blueprint $table) {
$table->id();
$table->string('noticeTitle');
$table->string('noticeDesc');
$table->string('file')->nullable();
$table->unsignedBigInteger('batch_id');
$table->foreign('batch_id')->references('id')->on('batches');
$table->timestamps();
});
Batch Migration:
Schema::create('batches', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->timestamps();
});
Data dump from db is:
"id" => 1
"noticeTitle" => "Quae ea est temporib"
"noticeDesc" => "<p>sa</p>"
"file" => null
"batch_id" => 2
"created_at" => "2020-07-27 16:09:52"
"updated_at" => "2020-07-27 16:09:52"
]
Notice model
public function batches()
{
return $this->belongsTo(Batch::class);
}
Batch Model
public function notice()
{
return $this->hasMany(Notice::class);
}
Notice controller
public function index(){
$notices = Notice::all();
return view('admin.notice.list')
->with('notices', $notices);
}
public function store(Request $request)
{
$this->validate($request, [
'noticeTitle' => 'required',
'noticeDesc' => 'required',
]);
$notice = new Notice;
$notice->noticeTitle = $request->input('noticeTitle');
$notice->noticeDesc = $request->input('noticeDesc');
$notice->batch_id = $request->input('targetedGroup');
if($request->hasFile('file')) {
$noticeTitle = $request->input('noticeTitle');
$filename = $request->file->getClientOriginalName();
$request->file->storeAs('public/noticeFile/additionalFiles', $noticeTitle.'_'.$filename);
$path = $noticeTitle.'_'.$filename;
$notice->file = $path;
}
try{
$notice->save();
Session::flash('success', 'Notice Saved');
return redirect()->route('notice.index');
}
catch (\Throwable $th){
Session::flash('danger', 'Something went wrong');
return redirect()->route('notice.index');
}
}
Now I want to get batch name from batch_id
First, you might want to change the function names of your relationships. Your notice has only one batch, so it should be public function batch() and a batch has several notices, so public function notices().
You can acces your relationships like any attribute, so in your blade:
#foreach($notices as $notice)
#php $batch = $notice->batch; #endphp
{{$batch->name}}
#endforeach
Or even shorter (if you don't plan on using the related batch for anything else)
#foreach($notices as $notice)
{{$notice->batch->name}}
#endforeach
This is all explained in the Laravel documentation: https://laravel.com/docs/7.x/eloquent-relationships
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 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.
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;
We are having a strange issue with Laravel 5 in that it is refusing to store the checkbox value.
We are adapting the existing registration form that comes bundled with Laravel 5 and we are adding an optin checkbox but it seems the model does not recognise this as a field even though we are adding it as a field in the migration file.
Any help on this would be appreciated.
Mirgration File:
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('first_name');
$table->string('last_name');
$table->string('email')->unique();
$table->string('password', 60);
$table->date('dob');
$table->boolean('optin')->nullable();
$table->rememberToken();
$table->timestamps();
});
}
Then we add it to the register.blade.php file:
<div class="form-group">
<label class="col-md-4 control-label">Optin</label>
<div class="col-md-6">
<input type="checkbox" class="form-control" name="optin">
</div>
</div>
At the point of creating the User model, we check the value of the checkbox and assign it.
protected function create(array $data)
{
//this does return 1 or 0 as expected
$optin = ($data["optin"] == "on") ? 1 : 0;
return User::create([
'first_name' => $data['first_name'],
'last_name' => $data['last_name'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
'dob' => $data['dob'],
'optin' => $optin
]);
}
But at this point the field is null. No value is entered into the database...
Have you put the field 'optin' in the $fillable array within the model? Otherwise you cant create a User with 'optin' using the static create method.
//File: User.php
protected $fillable = ['optin'];
The model already has a static create() function. Therefore, when you make a call like User::create($data) from your controller, your function is not called.
My approach is to change the name of your function and make it static.
Update
Also you can override the create function:
public static function create(array $attributes)
{
$attributes["optin"] = ($attributes["optin"] == "on") ? 1 : 0;
return parent::create($attributes);
}