How to store and update multiple data in Laravel - php

I have two tables in my database: role's table and role membership's table
role's table
Schema::create('roles', function (Blueprint $table) {
$table->increments('id');
$table->string('RoleName');
$table->boolean('IsAllCategory')->nullable()->default(0);
$table->boolean('IsUserCanLogin')->nullable()->default(1);
$table->timestamps();
});
role membership's table
Schema::create('role_memberships', function (Blueprint $table) {
$table->increments('id');
$table->integer('role_id');
$table->string('MembershipName');
$table->text('MembershipValue');
$table->timestamps();
});
I have a row data in my role's table with RoleName = 'Admin', then I set the membership.. everytime I store role membership data into database, it will store as two rows with same role_id..
This is my controller of Role membership
public function show($id)
{
$role = Role::findOrFail($id);
$postAdMaxImage = DB::table('role_memberships')->where('role_id', $role->id)->where('MembershipName' , 'PostAdMaxImage')->first();
$postAdExpiredDay = DB::table('role_memberships')->where('role_id', $id)->where('MembershipName' , 'PostAdExpiredDay')->first();
return view('pages/back-end/forms/role/membership')->with('role', $role)
->with('postAdMaxImage', $postAdMaxImage)
->with('postAdExpiredDay', $postAdExpiredDay);
}
public function update(Request $request, $id)
{
$role = Role::findOrFail($id);
$membership = [
['role_id' => $id, 'MembershipName' => 'PostAdMaxImage', 'MembershipValue' => $request->PostAdMaxImage ? $request->PostAdMaxImage : ''],
['role_id' => $id, 'MembershipName' => 'PostAdExpiredDay', 'MembershipValue' => $request->PostAdExpiredDay ? $request->PostAdExpiredDay : '']
];
DB::table('role_memberships')->insert($membership);
return response()->json(array($role, $membership));
}
The first problem is in show function.. I can not use first().. I want to get the data to show it into my view
<div class="form-group">
<div class="col-md-6">
<label>Membership</label><br>
<label>Maximum Gambar untuk Iklan</label>
<div class="row">
<div class="col-md-10">
<input type="text" name="PostAdMaxImage" class="form-control" value="{{$postAdMaxImage->MembershipValue}}">
</div>
<div class="col-md-2" style="padding: 0 !important">
<h5>Gambar</h5>
</div>
</div>
</div>
</div>
<div class="form-group">
<div class="col-md-6">
<label>Masa Berlaku Iklan</label>
<div class="row">
<div class="col-md-10">
<input type="text" name="PostAdExpiredDay" class="form-control" value="{{$postAdExpiredDay->MembershipValue}}>
</div>
<div class="col-md-2" style="padding: 0 !important">
<h5>Hari</h5>
</div>
</div>
</div>
</div>
The second problem is, when I want to edit the membership.. It will store as new two rows, not update the last two rows

To get the values use the value function
$postAdMaxImage = DB::table('role_memberships')->wh‌​ere('role_id', $role->id)->where('MembershipName' , 'PostAdMaxImage')->value('MembershipValue');
$postAdExpiredDay = DB::table('role_memberships')->where('role_id', $id)->where('MembershipName' , 'PostAdExpiredDay')->value('MembershipValue');
change your view to:
value="{{$postAdMaxImage}}"
value="{{$postAdExpiredDay}}"
In the second question you need to alter your update function to update the fields not create new ones
public function update(Request $request, $id)
{
$PostAdMaxImage= $request['PostAdMaxImage'];
$PostAdExpiredDay = $request['PostAdExpiredDay'];
DB::table('role_memberships')->where('role_id',$id)->where('MembershipName','PostAdMaxImage')->update(['MembershipValue'=>$PostAdMaxImage]);
DB::table('role_memberships')->where('role_id',$id)->where('MembershipName','PostAdExpiredDay')->update(['MembershipValue'=>$PostAdExpiredDay]);
return response()->json(array($role, $membership));
}

Related

Laravel - Model attributes stay NULL in database after creation

I have a model named Articles which contained three attributes: 'title', 'subtitle' and 'body' and it worked perfectly but after adding four columns to that model ('subtitle2', 'body2', 'subtitle3' and 'body3') the newly added columns stay NULL after creating articles.
There is clearly something that I missed but I can't figure out what.
This is the migration:
public function up()
{
Schema::table('articles', function (Blueprint $table) {
$table->string('subtitle2')->nullable()->default(null);
$table->text('body2')->nullable()->default(null);
$table->string('subtitle3')->nullable()->default(null);
$table->text('body3')->nullable()->default(null);
});
}
After migrating I edited my app/Http/Models/Article.php and it looks like this:
protected $fillable = [
'title',
'subtitle',
'body',
'subtitle2',
'body2',
'subtitle3',
'body3',
];
This is my app/Http/Livewire/CreateArticle.php
class CreateArticle extends Component
{
use WithFileUploads;
public $title;
public $subtitle;
public $body;
public $category;
public $subtitle2;
public $body2;
public $subtitle3;
public $body3;
public $temporary_images;
public $images = [];
public $article;
public function store()
{
$this->validate();
$this->article = Category::find($this->category)->articles()->create($this->validate());
$this->article->user()->associate(Auth::user());
$this->article->save();
if(count($this->images)){
foreach($this->images as $image){
$newImage = $this->article->images()->create(['path'=>$image->store('images', 'public')]);
dispatch(new ResizeImage($newImage->path, 600, 400));
}
}
}
And finally I added these lines to the form:
{{-- INSERT SUBTITLE 2 --}}
<div class="mb-3">
<label for="subtitle2" class="form-label">Second paragraph subtitle</label>
<input type="text" wire:model="subtitle2" class="form-control" id="subtitle2">
</div>
{{-- INSERT PARAGRAPH 2 --}}
<div class="mb-3">
<label for="body2" class="form-label">Second paragraph</label><br>
<textarea class="form-control" wire:model="body2" id="body2" cols="30" rows="3"></textarea>
</div>
{{-- INSERT SUBTITLE 3 --}}
<div class="mb-3">
<label for="subtitle3" class="form-label">Third paragraph subtitle</label>
<input type="text" wire:model="subtitle3" class="form-control" id="subtitle3">
</div>
{{-- INSERT PARAGRAPH 3 --}}
<div class="mb-3">
<label for="body3" class="form-label">Third paragraph</label><br>
<textarea class="form-control" wire:model="body3" id="body3" cols="30" rows="3"></textarea>
</div>
dd($this); is returning the following
Tinker is showing all columns
You need to specify
protected $rules
in order to use
$this->validate()
Assuming the dd(); image you provided is the latest. I can see the new columns does not exists in database. ('subtitle2', 'body2', 'subtitle3' and 'body3') all these are not available in list.
so I think you are missing to run the migrate command
php artisan migrate

Laravel : How to Create Dropdown to Select FOREIGN KEY from Other Table?

i want to ask you how to select FOREIGN KEY (from "doa_id in "doas" table) when user create a new data (to the "notes table) in a form. This is my code :
NoteController.php
public function create()
{
return view('note/create');
}
public function store(Request $request)
{
$userId = Auth::user()->id;
Note::create([
'title' => $request->title,
'detail' => $request->detail,
'user_id' => $userId,
'mood_id' => $request->mood_id,
'doa_id' => $request->doa_id,
]);
return redirect('notes');
}
2021_05_28_020438_create_notes_table.php migration
class CreateNotesTable extends Migration
{
public function up()
{
Schema::create('notes', function (Blueprint $table) {
$table->id('note_id');
$table->string('title');
$table->date('created_at');
$table->date('updated_at');
$table->text('detail');
$table->unsignedBigInteger('user_id');
$table->foreign('user_id')->references('id')->on('users');
//mood FK
$table->unsignedBigInteger('mood_id');
$table->foreign('mood_id')->references('mood_id')->on('moods');
//doa FK
$table->unsignedBigInteger('doa_id');
$table->foreign('doa_id')->references('doa_id')->on('doas');
});
}
public function down()
{
Schema::dropIfExists('notes');
}
}
and this is my dropdown html :
<div class="container">
<label class="form-label text-white" style="font-weight: bold;" for="doa">Doa terkait</label>
<select class="form-select" style="color: #41A7A5" aria-label="Default select example">
<option selected>Pilih doa</option>
</select>
</div>
In Dropdown option, I want to show "doa_name" based on it's "doa_id"
Thank you :)
You can put the logic in the NoteController and the view. For example, to get a collection of all options for the foreign key, pass the collection to the view.
public function create()
{
$doas = Doas::all();
return view('note/create', compact('doas'));
}
Then on the view, you can perform a foreach loop using the select HTML tag.
<div class="container">
<label class="form-label text-white" style="font-weight: bold;" for="doa">Doa terkait</label>
<select class="form-select" style="color: #41A7A5" aria-label="Default select example">
#foreach ($doas as $doa)
<option value="{{$doa-id>}}">{{$doa->name}}</option>
#endforeach
</select>
</div>
After this, it's just using the input in your store() method.

Laravel 8 - Save multiple checkbox selections with separate field to pivot table

Background:
Laravel 8 + Bootstrap 5
I'm pulling a list of licence categories from database to the form.
In the form user is asked to tick which licence to assign to the user. (up to that point I'm OK)
Target
I'd like licence expiry date to be assigned to every category selected.
Code
blade.php
<div class="mb-1"><strong>Assign user's driving licence categories:</strong></div>
#foreach($categories as $category)
<div class="input-group mb-3">
<div class="input-group-text" style="width: 6ch !important;">{{$category->name}}</div>
<div class="input-group-text">
<input class="form-check-input" type="checkbox" name="categories[]" value="{{$category->id}}">
</div>
<div class="input-group-text">Expiry date</div>
<input class="form-control" type="date" name="expiry_date[]">
</div>
#endforeach
Form screenshot
pivot table migration
public function up()
{
Schema::create('driving_licence_category_user', function (Blueprint $table) {
$table->id();
$table->string('driving_licence_category_id');
$table->string('user_id');
$table->string('expiry_date')->nullable();
$table->timestamps();
});
}
models
User
public function drivingLicenceCategory()
{
return $this->belongsToMany('App\Models\DrivingLicenceCategory')
->withPivot('expiry_date')
->withTimestamps();
}
Licence
public function userHasDrivingLicenceCategory()
{
return $this->belongsToMany('App\Models\User');
}
UserController
public function store(Request $request)
{
$request->validate([
'first_name' => 'required',
'last_name' => 'required',
'email' => 'required',
'roles' => 'required',
'categories' => 'required',
'expiry_date' => 'required'
]);
$user = User::create($request->except(['roles', 'categories', 'expiry_date']))
->syncRoles($request->roles)
->drivingLicenceCategory()->sync($request->only('categories'));
//missing code to store the expiry_date information
return redirect()->route('users.index')->with('success', 'User added successfully.');
}
Thank you for spending time on this post :)

Method Illuminate\Database\Eloquent\Collection::books does not exist.(laravel)

I am beginner of laravel, I want to store a book to books database, but after click button, it shows "Method Illuminate\Database\Eloquent\Collection::books does not exist." What am I missing?
here are my codes.
BookController
public function create()
{
return view('books.create');
}
public function store(Request $request)
{
$this->validate($request, [
'book' => 'required|max:255',
'category' => 'required',
'quantity' => 'required|numeric',
'price'=>'required|numeric',
'info'=>'required'
]);
//$request->user()->member()->books()->create([
$member=auth()->user()->member()->get();
$member->books()->create([
'book' => $request->book,
'category' => $request->category,
'quantity' => $request->quantity,
'price'=>$request->price,
'info'=>$request->info
]);
return redirect('shops')->with('success', 'successful');
}
books.create
<form action="{{route('books.store')}}" method="POST" role="form">
#csrf
#method('POST')
<div class="form-group">
<label for="book">name:</label>
<input id="book" name="book" class="form-control" placeholder="enter book name">
</div>
<div class="form-group">
<label for="category">category:</label>
<input id="category" name="category" class="form-control" placeholder="enter category">
</div>
<div class="form-group">
<label for="quantity">quantity:</label>
<input id="quantity" name="quantity" class="form-control" placeholder="enter quantity">
</div>
<div class="form-group">
<label for="price">price:</label>
<input id="price" name="price" class="form-control" placeholder="enter price">
</div>
<div class="form-group">
<label for="info">info:</label>
<textarea id="info" name="info" class="form-control" rows="10" placeholder="enter info"></textarea>
</div>
<button type="submit" class="btn-sm btn-primary">create</button>
</form>
User and Member is one to one relation, and Book belongs to one Member
Book Model
public function member()
{
return $this->belongsTo(Member::class);
}
protected $fillable = ['book','category','quantity','price','info'];
Member Model
public function books()
{
return $this->hasMany(Book::class);
}
public function user()
{
return $this->belongsTo(User::class);
}
User Model
public function member()
{
return $this->hasOne(Member::class);
}
books,user and member migration
books migration
public function up()
{
Schema::create('books', function (Blueprint $table) {
$table->increments('id');
$table->unsignedInteger('member_id');
$table->foreign('member_id')->references('id')->on('members')->onDelete('cascade');
$table->string('name');
$table->integer('quantity');
$table->integer('price');
$table->string('path');
$table->string('info');
$table->string('category');
$table->timestamps();
});
}
member migration
public function up()
{
Schema::create('members', function (Blueprint $table) {
$table->increments('id');
$table->unsignedbigInteger('user_id');
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->string('sex');
$table->string('email');
$table->string('address');
$table->string('tel');
$table->timestamps();
});
}
user migration
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->foreignId('current_team_id')->nullable();
$table->text('profile_photo_path')->nullable();
$table->timestamps();
});
}
You are receiving a Collection from this chain of calls:
$member = auth()->user()->member()->get();
get is going to always return a Collection when called on a relationship method. If you want a single model you can call first instead:
$member = auth()->user()->member()->first();
Though first could return null so you may need to check that.
Another method to access the result of this relationship would be to use the dynamic property for the relationship member:
$member = auth()->user()->member;
Since that relationship is defined as a HasOne it knows to load it for a single result or null.
Assuming $member isn't null at this point you should be fine with the rest how it is.
$member=auth()->user()->member()->get(); returns a collection not an object of Member class. Use $member=auth()->user()->member()->first(); or $member=auth()->user()->member;
Try this
public function store(Request $request)
{
$this->validate($request, [
'book' => 'required|max:255',
'category' => 'required',
'quantity' => 'required|numeric',
'price'=>'required|numeric',
'info'=>'required'
]);
$member=auth()->user()->member;
if($member){
$member->books()->create([
'book' => $request->book,
'category' => $request->category,
'quantity' => $request->quantity,
'price'=>$request->price,
'info'=>$request->info
]);
return redirect('shops')->with('success', 'successful');
}
//Member is not found, return with error
return redirect()->back()->with('error', 'Member not found');
}
That error is due to the fact that this call $member=auth()->user()->member()->get();. It's supposed to return a Collection of Member.
So when you try to call books on a collection hold by the variable member It' won't succeed as Illuminate\Support\Collection Class doesn't define a method books you have to loop trought that collection by using a foreach loop or a each or map method from Collection.
$member->each(function($member){
$member->books()->create([
//
]);
});
Or has you have already define in User Model that user will always have a single Member by using hasOne method.
So you can use auth()->user()->member()->first(); which return a single instance of type Member on which you call books method but with that you have to be sure that the Authenticated use has already one member which is attached to him to avoid any error. even though that is the case you can always check if variable $member is not null with an if statement
$member = auth()->user()->member()->first();
if($member){
// here you can have access to `books`
$member->books()->create([
//...
]);
}

laravel Cannot save records to DB

I am building a blog system with laravel.
Now I have a blogger table that has a name, email address, and password.
In addition to the default account table, I want to save a profile image and introduction.
They belong to the blogger table in my case.
But I cannot save those two records.
I cannot figure out why profile records cannot be inserted into my DB.
And my user role is a blogger.
I can see ?_token on the url.
blogger table
Schema::create('bloggers', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
blogs table
Schema::create('blogs', function (Blueprint $table) {
$table->bigIncrements('id');
$table->integer('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('bloggers');
$table->string('image');
$table->string('introduction');
$table->timestamps();
});
blogger.php
public function blogs()
{
return $this->hasMany(Blog::class, 'user_id');
}
blog.php
public function user(){
return $this->belongsTo(Blogger::class, 'user_id');
}
bloggersController.php
public function store(Request $request, Blogger $blogger_id){
$blogger_id = DB::table('bloggers')->where('id', $blogger_id)->get();
Auth::guard('blogger')->user();
if($request->hasfile('image')){
$file = $request->file('image');
$ext = $file->getClientOriginalExtension();
$filename = time().'.'.$ext;
$file->move('bloggers/', $filename);
$blog = Blog::updateOrCreate(
['user_id' => $blogger_id],
[
'image'=>$filename,
'introduction' => $request->introduction,
]
);
}
return view('bloggers.create')->with('bloggers', Blogger::all())->with('blogs', Blog::all());
}
web.php
Route::get('/create', 'BloggersController#store')->name('blogs.store');
create.blade.php
<form action="{{ route('blogs.store') }}" enctype="multipart/form-data">
#csrf
<img src="{{asset('blog-image/alexandre-chambon-zxmSX2-GQBc-unsplash.jpg')}}" alt="card-background" class="card-img">
<div class="image-preview" id="imagePreview">
#if(empty(Auth::guard('blogger')->user()->blog->image))
<img src="{{asset('avatar/avatar.png')}}" id="image-preview__image" alt="avatar">
#else
<img src="{{asset('bloggers/')}}/{{ Auth::guard('blogger')->user()->blog->image}}" id="preview" alt="profile image">
#endif
</div>
<input type="text" class="name" value="{{ Auth::guard('blogger')->user()->name }}" name="name">
<textarea name="introduction" id="" cols="30" rows="10" class="profile">
#if(!empty(Auth::guard('blogger')->user()->blog->introduction)){{ Auth::guard('blogger')->user()->blog->introduction }}#endif
</textarea>
<div class="preview">
<input type="file" id="file" class="file1" accept="image/*" name="image">
<label for="file">
Add profile photo
</label>
</div>
<button type="submit" id="register">Register</button>
</form>
public function store(Request $request, Blogger $blogger){
// If you are using route model you already have a model instance
$blogger_id = $blogger->id
//Auth::guard('blogger')->user();
if($request->hasFile('image')){
$file = $request->file('image');
$ext = $file->getClientOriginalExtension();
$filename = time().'.'.$ext;
$file->move(public_path("bloggers"), $filename);
$path = '/bloggers/' . $filename;
$blog = Blog::updateOrCreate(
['user_id' => $blogger_id],
[
'image'=>$filename,
'introduction' => $request->introduction,
]
);
}
return view('bloggers.create')->with('bloggers', Blogger::all())->with('blogs', Blog::all());
}

Categories