Livewire - I only can Add records to the pivot table - Through checkboxes - laravel

I am only able to add records to the pivot table. Really strugling on removing an entry from the pivot table
Livewire Component
<?php
namespace App\Http\Livewire;
use App\Models\User;
use App\Models\Company;
use Livewire\Component;
use Livewire\WithPagination;
class UserAssignCompanySection extends Component
{
use WithPagination;
public $sortBy = 'id';
public $sortAsc = false;
public $user;
public $companies;
public $search;
public $confirmingCompanyRemoval = false;
public $userCompanies = [];
protected $rules = [
'user.name' => 'required',
'user.email' => 'required',
'user.title' => 'required',
'user.first_name' => 'required',
'user.last_name' => 'nullable',
'user.mobile' => 'nullable',
'user.phone' => 'nullable',
'user.is_customer' => 'boolean',
'user.is_provider' => 'boolean',
'userCompanies' => 'required|array',
];
// Table Sort
public function sortBy($field)
{
if($field == $this->sortBy){
$this->sortAsc = !$this->sortAsc;
}
$this->sortBy = $field;
}
// public function updatedUserCompanies()
// {
// $var1 = array_diff(Company::pluck('id')->toArray(),$this->userCompanies);
// dd(Company::pluck('id')->toArray(), $this->userCompanies);
// dd($var1);
// $this->user->companies()->sync($this->userCompanies);
// }
public function updatedUserCompanies()
{
//dd($this->userCompanies);
$this->user->companies()->sync($this->userCompanies);
}
public function mount(User $user)
{
$this->user = $user;
$this->companies = Company::all();
$this->userCompanies = $user->companies()->pluck('company_id')->toArray();
//dd($this->userCompanies);
}
public function render()
{
//$this->user->companies()->sync($this->userCompanies);
return view('livewire.user-assign-company-section');
}
}
<div>
<div class="grid grid-cols-1 text-left xl:grid-cols-6">
<div class="col-span-3 p-4">
<p class="text-lg underline">Name</p>
<x-jet-input wire:model.defer="user.name" id="name" type="text" disabled class="block w-full mt-1 bg-gray-100" />
<x-jet-input-error for="user.name" class="mt-2" />
<br>
#json($userCompanies);
{{-- #foreach ($userCompanies as $item)
{{ $item }}
#endforeach --}}
#foreach($companies as $company)
<div class="mt-1">
<input wire:model="userCompanies" type="checkbox" value="{{ $company->id }}">
{{ $company->name }} <br>
</div>
#endforeach
<br>
{{-- <x-jet-button>Back</x-jet-button> --}}
<br>
</div>
</div>
</div>
When i click on the checbox with company_id = 3 a sting gets added to $this->userCompanies livewire property
something like this
[1,2,"3"];
When i uncheck ids such as 1 and 2 (which was retreived through the DB won't get deleted)
I think it tries to delete a string such as "1" from an array based on integers

If property is array then model have to be declared as array (with dot notation). Try some like this:
#foreach($companies as $i => $company)
<div class="mt-1">
<input wire:model="userCompanies.$i" type="checkbox" value="{{$company->id }}">
{{ $company->name }} <br>
</div>
#endforeach

Related

Livewire: problem whit display data and form

I have problem with display data and form on one page.
Display data from database disappear after write in textarea any word. The same problem ist when i click on submit. In debugger is only data from first query, from second is cleared.
I try with one query (second), but it's the same.
My example code
route web:
Route::middleware(['auth:sanctum', 'verified'])->get('/tickets/show/{slug}', Tickets\Show::class)->name('tickets.show');
Livewire:
public $ticket;
public $slug;
public $posts;
public $content_post;
public $ticket_id;
public function mount($slug){
$this->ticket = Tickets::where('tickets.id','=', $slug)->join('users', 'users.id', '=', 'tickets.user_id')
->select('users.email','users.phone','users.username','users.first_name','users.last_name','tickets.user_id','tickets.created_at',
'tickets.id', 'tickets.subject','tickets.status_id','tickets.admin_id')->first();
$this->posts = TicketsPost::where('tickets_posts.ticket_id','=', $slug)->join('users', 'users.id', '=', 'tickets_posts.user_id')
->select('users.email','users.username','users.first_name','users.last_name','tickets_posts.user_id','tickets_posts.created_at',
'tickets_posts.ticket_id','tickets_posts.post')->get();
}
public function addPost()
{
$this->validate([
'content_post' => 'required'
]);
$user_id = Auth::user()->getAuthIdentifier();
TicketsPost::create([
'ticket_id' => $this->ticket_id,
'user_id' => $user_id,
'post' => $this->content_post,
]);
}
public function render()
{
return view('livewire.tickets.show');
}
View:
<p >#{{$ticket->id}}</p>
<p >{{$ticket->subject}}</p>
#foreach($posts as $post)
<p >{{$post->first_name}} {{$post->last_name}}</p>
<p >{{ date('d.m.Y H:i',strtotime($post->created_at)) }}</p>
<p > {{$post->post}}</p>
#endforeach
<form >
<input type="hidden" name="ticket_id" value="2" wire:model="ticket_id">
<textarea name="content_post"
class=""
rows="5" required="" placeholder="Treść wiadomości" wire:model="content_post"></textarea>
#error('content_post') <span class="text-red-500">{{ $message }}</span>#enderror
<button wire:click.prevent="addPost()" type="submit" class="">
<span id="btn_text" class="ml-2">Dodaj</span>
</button>
</form>
In Livewire, make sure your component has a single-level root element only.
And, don't forget to add wire:key in your element inside every loop in a blade.
Your loop should be as;
#foreach($posts as $key => $post)
<div wire:key="{{'post'.$key}}">
<p>{{$post->first_name}} {{$post->last_name}}</p>
<p >{{ date('d.m.Y H:i',strtotime($post->created_at)) }}</p>
<p > {{$post->post}}</p>
</div>
#endforeach

Bleaching the page when submitting the form with livewire

In login form i used livewire and when i out focus of phone field my webpage its been white
please help me thanks <3
view code:
<form wire:submit.prevent="login">
<fieldset class="form-label-group form-group position-relative has-icon-left">
<input wire:model.debounce.500ms="phone" type="text" class="form-control" id="phone" placeholder="شماره تماس">
<div class="form-control-position">
<i class="feather icon-phone"></i>
</div>
<label for="phone">شماره تماس</label>
</fieldset>
#error('phone') <span class="text-danger">{{ $message }}</span> #enderror
<button type="submit" class="btn btn-primary float-left btn-inline" wire:click.prevent="login">ورود</button>
</form>
controller code:
class Login extends Component
{
public $phone;
protected $rules = [
'phone' => ['required', 'regex:/^09(1[0-9]|3[1-9]|2[1-9])-?[0-9]{3}-?[0-9]{4}$/', 'exists:users,phone']
];
public function updatedPhone($name)
{
$this->validate($name);
}
public function login(Request $request)
{
$validData = $this->validate();
$user = User::wherePhone($validData['phone'])->first();
dd($user);
$request->session()->flash('auth', [
'user_id' => $user->id,
'remember' => $request->has('remember'),
]);
$code = ActiveCode::generateCode($user);
$user->notify(new ActiveCodeNotification($code, $user->phone));
dd('done');
}
public function render()
{
return view('livewire.auth.login')
->layout('livewire.auth.layouts.layouts');
}
}
Your updatePhone method is supposed to receive $value from input binded with wire:model so you have to pass a key-value to validate method:
public function updatePhone($value)
{
$this->validate($this->rules); // protected prop with key-value rules defined
}

Got issues with Assigning User to any Shop in Laravel

I have an issue with assign user to any Shop. i created Shop A and Shop B and want to assign user to each shop. Its work fine, when im assign any user to Shop A. however, when i try assign user to Shop B , user alway got in to Shop A not Shop B.
// My User Model
public function shop()
{
return $this->belongsTo(\App\Shop::class, 'user_id');
}
// My Shop Model
public function user()
{
return $this->hasMany(\App\User::class, 'user_id');
}
// My UserController
public function index()
{
$users = User::all();
$shops = Shop::all();
// return view('user', compact('users', 'shops'));
return UserResource::collection($users);
}
public function create(Request $request)
{
$request->validate([
'name' => 'required',
'email' => 'required',
'password' => 'required',
]);
$user = new user();
$user->user_id = auth()->user()->id;
$user->name = $request->name;
$user->email = $request->email;
$user->password = bcrypt($request->password);
$user->save();
return new UserResource($user);
}
// My User.blade.php Code
#extends('layouts.app')
#section('content')
<div class="container" style="width: 50%">
<h2>Create User</h2>
#if ($errors->any())
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
<form action="user" method="POST">
#csrf
<div class="form-group">
<label for="name">Name</label>
<input type="text" name="name" class="form-control">
</div>
<div class="form-group">
<label for="email">Email</label>
<input type="text" name="email" class="form-control" >
</div>
<div class="form-group">
<label for="password">Password</label>
<input type="password" class="form-control" name="password">
</div>
<div class="form-group">
<label for="shop">Shop</label>
<select name="shops" class="form-control">
#foreach($shops as $shop)
<option value="{{ $shop->id }}">
{{ $shop->name }}
</option>
#endforeach
</select>
</div>
<button class="btn btn-primary">Submit</button>
</form>
</div>
#endsection
Am i doing something wrong with Relationship?
You have two distinct relation from the Shop model to the User model.
// Shop Model
public function users()
{
return $this->hasMany(\App\User::class);
}
public function owner()
{
return $this->belongTo(\App\User::class);
}
If in your controller you want to assign the shop to the user created
public function create(Request $request)
{
$request->validate([
'name' => 'required',
'email' => 'required',
'password' => 'required',
]);
$user = new user();
$user->user_id = auth()->user()->id;
$user->shop_id = $request->shops;
$user->name = $request->name;
$user->email = $request->email;
$user->password = bcrypt($request->password);
$user->save();
return new UserResource($user);
}
For the User Model, you need to define the two different relation with Shop Model
public function shop()
{
return $this->belongsTo(\App\Shop::class); //remove the foreign key or change it to 'shop_id'
}
public function ownedShops()
{
return $this->hasMany(\App\Shop::class);
}

"Trying to get property 'id' of non-object (View: C:\xampp\htdocs\CERCAA\resources\views\admin\posts\edit.blade.php)"

When I am editing my post then I am prompted with the following error message
Trying to get property 'id' of non-object (View: C:\xampp\htdocs\CERCAA\resources\views\admin\posts\edit.blade.php)
public function update(Request $request, $id)
{
$this->validate($request, [
'title' => 'required',
'content' => 'required',
'category_id' => 'required'
]);
$post = Post::find($id);
if($request->hasFile('featured'))
{
$featured = $request->featured;
$featured_new_name = time() . $featured->getClientOriginalName();
$featured->move('uploads/posts', $featured_new_name);
$post->featured = 'uploads/posts/'.$featured_new_name;
}
$post->title = $request->title;
$post->content = $request->content;
$post->category_id = $request->category_id;
$post->save();
Session::flash('success', 'Post updated successfully.');
return redirect()->route('posts');
}
and blade code
<div class="form-group">
Select a Category
#foreach($categories as $category)
id}}"
#if($post->$category->id == $category->name)
selected
#endif
{{$category->name}}
#endforeach
List item
My Post method for post and category
namespace App;
use Illuminate\Database\Eloquent\Model;
class Category extends Model
{
protected $table = 'categories'; // here set table's name
protected $primaryKey = 'id'; // here set table's primary Key field name
protected $fillable = ['id']; // here set all table's fields name
public function posts()
{
return $this->hasMany('App\Post');
}
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Post extends Model
{
public function category()
{
return $this->belongsTo('App/Category');
}
public function getFeaturedAttribute($featured)
{
return asset($featured);
}
use SoftDeletes;
protected $dates=['deleted_at'];
protected $fillable=['title','content','category_id','featured','slug'];
}
}
Edit.blade.php
#extends('layouts.app')
#section('content')
<div class="row">
<div class="col-lg-12">
<div class="card">
<div class="card-header bg-info">
<div class="text-center">
<h4 class="m-b-0 text-white">
<div class="panel panel-default">
<div class="panel-heading">
Edit Post:{{$post->title}}
</div>
<div class="panel-body">
<form action="{{route('post.update', ['id'=>$post->id])}} " method="post" enctype="multipart/form-data">
{{csrf_field()}}
<div class="form-group">
<label for ="title">Title</label>
<input type="text" name="title" class="form-control" value="{{$post->title}}">
</div>
<div class="form-group">
<label for ="featured">Featured image</label> <input type="file" name="featured" class="form-control">
</div>
<div class="form-group">
<label for ="category">Select a Category</label>
<select name="category_id" id="category" class="form-control">
#foreach($categories as $category)
<option value="{{$category->id}}"
#if(property_exists($post, 'category') && $post->$category['id'] == $category->name)
selected
#endif
>{{$category->name}}</option>
#endforeach
</select>
</div>
<div class="form-group">
<label for ="content">Content</label>
<textarea name="content" id="content" cols="5" rows="5" class="form-control"> {{$post->content}}</textarea>
</div>
<div class="form-group">
<div class="text-center">
<button class="btn btn-success" type="submit"> Update Post</button>
</div>
</div>
</form>
</div>
</div>
</h4>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- Row -->
#stop
Controller...
public function store(Request $request)
{
$this->validate($request, [
'title' =>'required',
'featured'=>'required|mimes:jpeg,pdf,docx,png:5000',
'file'=>'required|mimes:jpeg,pdf,docx,png:5000',
'content'=>'required',
'category_id'=>'required',
]);
$featured= $request->featured;
$featured_new_name=time().$featured->getClientOriginalName();
$featured->move('uploads/posts', $featured_new_name);
$file=$request->file;
$file_name=time().$file->getClientOriginalName();
$file->move('uploads/posts', $file_name);
$post = Post::create([
'title'=>$request->title,
'content'=>$request->content,
'featured'=>'uploads/posts/'. $featured_new_name,
'file'=>'uploads/posts'. $file_name,
'category_id'=>$request->category_id,
'slug'=>str_slug($request->title)
]);
Session::flash('success', 'New Blog has been Published on Website for Particular Menu');
return redirect()->back();
}
This the area in your blade where you are getting the issue:
<label for ="category">Select a Category</label>
<select name="category_id" id="category" class="form-control">
#foreach($categories as $category)
<option value="{{$category->id}}"
#if(property_exists($post, 'category') && $post->$category['id'] == $category->name)
selected
#endif
>{{$category->name}}</option>
#endforeach
</select>
Where are you fetching and providing $categories to this blade template? I mean the controller method which loads the edit blade?
Can you post that code as well?
And please update your question instead of posting answers.

Total, Quantity, Price in Laravel

I have a table named 'products' with 5 fields (id, title, price, quantity, total).
My goal is to calculate via the form products.create the total, price * quantity.
Database - products
public function up()
{
Schema::create('products', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('title');
$table->integer('quantity');
$table->double('price');
$table->double('total')->nullable();
$table->timestamps();
});
}
Model - product
protected $fillable = ['title', 'quantity', 'price', 'total'];
public function setTotalAttribute()
{
$this->total = $this->quantity * $this->price;
}
public function getTotalAttribute($value)
{
return $value;
}
** Controller - ProductController**
public function index()
{
$products = Product::oldest()->paginate(5);
return view('admin.products.index', compact('products'))
->with('i', (request()->input('page', 1)-1)*5);
}
public function create()
{
$products = Product::all();
return view('admin.products.create', compact('products'));
}
public function store(Request $request)
{
$request->validate([
'title' => 'required',
'quantity' => 'required',
'price' => 'required',
'total' => 'required'
]);
Product::create($request->all());
return redirect()->route('products.index')
->with('success', 'save');
}
My problem is in my view "products.create" I have 3 fields when I encode the 3 fields, nothing happens ???
Products.create
<form class="panel-body" action="{{route('products.store')}}" method="POST" novalidate>
#csrf
<fieldset class="form-group {{ $errors->has('title') ? 'has-error' : '' }}">
<label for="form-group-input-1">Title</label>
<input type="text" name="title" id="title" class="form-control" value="{{ old('title')}}"/>
{!! $errors->first('title', '<span class="help-block">:message</span>') !!}
</fieldset>
<fieldset class="form-group {{ $errors->has('quantity') ? 'has-error' : '' }}">
<label for="form-group-input-1">Quantity</label>
<input type="text" name="quantity" id="quantity" class="form-control" value="{{ old('quantity')}}"/>
{!! $errors->first('quantity', '<span class="help-block">:message</span>') !!}
</fieldset>
<fieldset class="form-group {{ $errors->has('price') ? 'has-error' : '' }}">
<label for="form-group-input-1">Price</label>
<input type="text" name="price" id="price" class="form-control" value="{{ old('price')}}"/>
{!! $errors->first('price', '<span class="help-block">:message</span>') !!}
</fieldset>
Back
<button type="submit" class="btn btn-sm btn-primary">Valider</button>
Thank you for help.
First of all you didn't send any total value...
$request->validate([
'title' => 'required',
'quantity' => 'required',
'price' => 'required',
]);
Just follow Eloquent ORM
$product = New Product();
$product-title = $request->title;
$product-quantity = $request->quantity;
$product-price = $request->price;
$product-total = $request->price * $request* quantity;
$product->save();
//redirect()
The mutator will receive the value that is being set on the attribute, so your mutator method should be like this on you Product model
public function setTotalAttribute()
{
$this->attributes['total'] = $this->quantity * $this->price;
}

Resources