Got issues with Assigning User to any Shop in Laravel - 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);
}

Related

How to update an array field in laravel?

EDIT FORM
<div class="form-group mb-3">
<label>Country:</label>
<div class="col-sm-4">
<select id="country-dd" name="country[]" class="js-example-basic-multiple form-control" multiple="multiple">
#foreach($countries as $country)
<option value="{{$country->id }}" {{in_array($country->id, explode(',',$user->country)) ? 'selected' : '' }}> {{$country->name}}</option>
#endforeach
</select>
</div>
</div>
CONTROLLER
public function updateuser(Request $request, $id)
{
// dd($request->all());
$request->validate([
'name'=>'required',
'email'=>'required|email|unique:users',
'country'=>'required',
'state'=>'required',
'city'=>'required',
'role_id'=>'required'
]);
$name = $request->name;
$email=$request->email;
$country=implode(',',$request->country);
$state=implode(',',$request->state);
$city=implode(',',$request->city);
$role_id=$request->role_id;
User::whereId($id)->update($request->all());
return redirect()->route('viewuser');
}
ROUTE
Route::put('/updateuser/{id}',[UserController::class,'updateuser'])->name('updateuser');
If I update a record. It just reloads the page and there is no error. Please correct me if I am doing wrong. Thanks in advance.
Try in the CONTROLLER:
public function updateuser(Request $request, $id)
{
$request->validate([
'name'=>'required',
'email'=>'required|email|unique:users',
'country'=>'required',
'state'=>'required',
'city'=>'required',
'role_id'=>'required'
]);
$user = User::findOrFail($id);
$user->name = $request->name;
$user->email=$request->email;
$user->country=implode(',',$request->country);
$user->state=implode(',',$request->state);
$user->city=implode(',',$request->city);
$user->role_id=$request->role_id;
$user->update();
return redirect()->route('viewuser');
}
Try in the form:
<form action="{{ route('updateuser',$data->id) }}" method="POST" enctype="multipart/form-data">
#method('PUT')
#csrf
ALL YOUR INPUTS HERE
<div class="card-footer">
<button type="submit" class="btn btn-primary mt-1 pr-4 pl-4">Update</button>
</div>
</form>
Route
Route::match(['put', 'patch'], 'updateuser/{id}', [UserController::class,'updateuser'])->name('updateuser');

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

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

After reflecting, I would like to display changes in form page

I would like to make a form.
After submitting the data,Redirect to the same page and reflect a change.
I thought return redirect should be a good way.
but it seems need to fetching the DB.
because 'ErrorException
Trying to get property 'id' of non-object (View:'error happens.
writing $user = \DB::table('users')->where('id', $request->id)... twice
is redundancy and cheesy.
Is there any good way to implement this.
class CertainController extends Controller
{
public function index(Request $request)
{
$user = \DB::table('users')->where('id', $request->id)->first();
$data = ['user' => $user];
return view('user.detail',$data);
}
public function update(Request $request)
{
\DB::table('users')
->where('id', $request->id)
->update([
$request->name => $request->value
]);
return redirect(route('user.detail', [
'user_id' => $request->id,
]));
}
}
web.php
Route::get('/user_detail', 'CertainController#index')->name('user.detail');
Route::get('/user_detail/update', 'CertainController#update')->name('user.detail.update');
blade
<form method ="GET" action={{ route('user.detail.update')}}>
<div class="form-group row">
<label>name</label>
<div class="col-md-6">
<input type = "hidden" name ="id" value="{{ $user->id }}"/>
<input type = "hidden" name = "column" value="name">
<input id="name" type="text" class="form-control #error('name') is-invalid #enderror" name="name" value="{{ $user->name }}" required autocomplete="name">
#error('')
{{ $message }}
#enderror
<button type = "submit" class ="button">submit</button>
</div>
</div>
</form>
You are looking for id in the index method,
$request->id
^^
But you are sending user_id from update method.
'user_id' => $request->id,
^^^^^
In a simple way, you can just do
return back();
here, back() is a helper function, which redirect back to where it came from.

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;
}

data is not submitting into db

I’m trying to signup user, initially it was working but now its not , when i enter data and click on signup then nothing happens, any solution to resolve this issue?
this is UsersController:
public function register(Request $request){
if($request->isMethod('post')){
$data = $request->all();
/*echo "<pre>"; print_r($data); die;*/
// Check if User already exists
$usersCount = User::where('email',$data['email'])->count();
if($usersCount>0){
return redirect()->back()->with('flash_message_error','Email already exists!');
}else{
$user = new User;
$user->name = $data['name'];
$user->email = $data['email'];
$user->password = bcrypt($data['password']);
$user->save();
// Send Confirmation Email
$email = $data['email'];
$messageData = ['email'=>$data['email'],'name'=>$data['name'],'code'=>base64_encode($data['email'])];
Mail::send('emails.confirmation',$messageData,function($message) use($email){
$message->to($email)->subject('Confirm your E-com Account');
});
return redirect()->back()->with('flash_message_success','Please confirm your email to activate your account!');
if(Auth::attempt(['email'=>$data['email'],'password'=>$data['password']])){
Session::put('frontSession',$data['email']);
if(!empty(Session::get('session_id'))){
$session_id = Session::get('session_id');
DB::table('cart')->where('session_id',$session_id)->update(['user_email' => $data['email']]);
}
return redirect('/cart');
}
}
}
}
this is registeration form:
<form id="registerForm" name="registerForm" action="{{ url('/user-register') }}" method="POST">{{ csrf_field() }}
<input id="name" name="name" type="text" placeholder="Name"/>
<input id="email" name="email" type="email" placeholder="Email Address"/>
<input id="myPassword" name="password" type="password" placeholder="Password"/>
<button type="submit" class="btn btn-default">Signup</button>
</form>
and this is route:
Route::post('/user-register','UsersController#register');
The basic registration method in laravel with validation and auto login
public function register(Request $request)
{
$this->validate($request, [
'name' => 'required',
'email' => 'required|email|unique:users,email',
'password' => 'required|min:6',
]);
$input = $request->all();
$input['password'] = Hash::make($input['password']);
$user = User::create($input);
Auth::login($user);
return redirect()->route('dashboard')
->with('success','Congratulation !!! You are registered successfully. Now you can login');
}
What is the error you will see in the blade template by adding this before form
#if($errors->all())
#foreach ($errors->all() as $error)
<div class="alert alert-danger">{{ $error }}</div>
#endforeach
#endif

Resources