How to Insert id from a Name in Laravel 5.3 Combobox - laravel

I want to insert the id of the supplier by choosing the name of the supplier from a combo box.
View
<label for="supplier">Supplier</label>
<input list="supplier" name="supplier" placeholder="Select Supplier" class="form-control">
#foreach($suppliers as $key=>$value)
<datalist id="supplier">
<option value="{{$key}}">{{$value}}
</datalist>
#endforeach
Controller
<?php
public function store(Request $request, User $user)
{
$user = Auth::user();
$product = new Product;
$request->user()->products()->create($request->all());
}
Model
protected $fillable = ['name', 'qty', 'bprice', 'sprice', 'edate'];
public function user()
{
return $this->belongsTo(User::class, user_id);
}

use this
public function store(Request $request, User $user)
{
$user = Auth::user();
$product = new Product;
$product->supplier_id = $request->supplier;
$product->price = $request->price; // if u hv it
. // finish the rest then
$user->products()->save($product);
// finish the rest
}

Related

show the data in dropdown fetched from database using laravel 8

i have to show the category values in dropdown in product form,the given code is from my view,the error is undefined $categories.this is my first code in laravel i dont know how to make changings in other files.which variable is used in foreach?or i have to create new function in ProductController?
<form action="/upload_product" method="post">
#csrf
<label>Choose Categories</label>
<select name="category_id" id="category" class="category">
<option disable selected>--select category--</option>
#foreach($categories as $item)
<option value="{{ $item->id }}">{{ $item->name}}</option>
#endforeach
</select>
<input type="text" name="name" placeholder="name">
<input type="number" name="sale_price" placeholder="sale_price">
</form>
Model Product.php
class Product extends Model
{
use HasFactory;
protected $table = 'products';
public $timestamps = true;
public function category(){
return $this->belongsTo('App\Models\Category');
}
}
Model Category.php
class Category extends Model
{
use HasFactory;
public $fillable = [ 'name' ];
protected $dates = [ 'deleted_at' ];
public $timestamps = true;
public function products (){
return $this->hasMany('App\Models\Product');
}
}
ProductController.php
<?php
namespace App\Http\Controllers;
use App\Models\Product;
use App\Models\Category;
use Illuminate\Http\Request;
class ProductController extends Controller
{
public function index()
{
$products = Product::all();
return view('products/index', ['products'=>$products]);
}
public function view()
{
$products = Product::with('category')->get();
$categories = Category::with('products')->get();
return view ('product.view')-> with([
'products' => $products,
'categories' => $categories,
]);
}
You have to use like below
public function index(){
$products = Product::all();
$categories = Category::with('products')->get();
return view('products.index', compact('products','categories'));
}
You don't have $categories in your index file.
Based on the index method, you're sendig just products:
public function index()
{
$products = Product::all();
return view('products/index', ['products'=>$products]);
}
So add categories too.
public function index()
{
$products = Product::get();
return view('products/index', ['products'=>$products]);
}
you can do this in three ways
public function index(){
$products = Product::all();
$categories = Category::with('products')->get();
return view('products.index', compact('products','categories'));
}
public function index(){
$products = Product::all();
$categories = Category::with('products')->get();
return view('products.index')->with(['products'=>$products,'categories'=>$categories]));
}
public function index(){
$data['products'] = Product::all();
$data['categories'] = Category::with('products')->get();
return view('products.index',$data);
}

Laravel - How to Prevent submit until all employee comments are filled in Laravel

I have project approval application. The employee can can for more than one project at a time. I have successfully written the code for project application, where the employee apply for projects.
Model
class Project extends Model
{
protected $table = 'projects';
protected $fillable = [
'id',
'employee_id',
'manager_id',
'is_approved',
'project_title',
];
public function projectcomment(){
return $this->hasMany('App\Models\ProjectComment');
}
public function employee()
{
return $this->belongsTo('App\Models\HrEmployee','employee_id');
}
}
class ProjectComment extends Model
{
protected $table = 'project_comments';
protected $fillable = [
'id',
'project_id',
'manager_comment',
];
public function project()
{
return $this->belongsTo('App\Models\Project','project_id');
}
}
Controller
public function manager_employee_all_project_approve(Request $request, $id)
{
$userCompany = Auth::user()->company_id;
$userEmployee = Auth::user()->employee_id;
$userId = Auth::user()->id;
$employeeids = DB::table('hr_employees')->select('id')->where('id', $employee->id)->first();
$employeeid = $employeeids->id;
$approved_count = Project::where('employee_id', $id)->count();
if ($approved_count > 0){
DB::beginTransaction();
try {
$approved_post = Project::where('employee_id', $id)->where('is_approved','!=', 3)
->update([
'is_approved' => 2
]);
}
view
<div class="row no-print">
<div class="col-12">
#if ($incompleteCount)
<i class="fas fa-check"></i> Approve
#endif
</div>
</div>
The manager adds comment on each of the project before he approves the project.
The comment field (manager_comment) is in another table, project_comments. From the Controller above, the manager approves the project (projects) by clicking on submit button and then is_approved is set to 2 (2 is for approve).
However, if the manager has not added comment (manager_comment in project_comments relating to project_id and employee_id), the application should prevent him from clicking the submit button. How do I achieve this?
Thank you.

How to update pivot table records using Eloquent in Laravel

Here is the source code of model and controller.
My Role.php
class Role extends Model
{
public function permissions()
{
return $this->belongsToMany('App\Models\Permission');
}
}
My Permission.php
class Permission extends Model
{
public function roles()
{
return $this->belongsToMany('App\Models\Role');
}
}
My Controller
class RoleController extends Controller
{
public function update(Request $request, $id) {
$role = Role::findOrfail($id);
$roleid = $role->id;
$permissions = $request->permissions;
foreach ($role as $roles) {
$roles->permissions()->updateExistingPivot($roleid, $permissions);
}
}
}
i will appreciate your help.Thanks
Assuming you want to 'sync' the permissions for the role, make this role only have the permissions that have been passed via the Request input:
public function update(Request $request, $id)
{
// validate the permissions array
...
$role = Role::findOrFail($id);
$role->permissions()->sync($request->input('permissions', []));
...
}
Laravel 6.x Docs - Eloquent - Relationships - Updating Many to Many Relationship - Syncing Associations sync
you can use laravel builtin functions
Add = attach
Delete = detach
Update = sync
more info
https://laravel.com/docs/5.8/eloquent-relationships#updating-many-to-many-relationships
Pass Array data while update data
class RoleController extends Controller
{
public function update(Request $request, $id) {
$input = $request->all();
$role = Role::findOrfail($id);
$roleid = $role->id;
$permissions = $input['permissions'];
foreach ($role as $roles) {
$roles->permissions()->updateExistingPivot($roleid, $permissions);
}
}
}
Create a controller with resource and assign the controller to web.php
Your form's action should be as follows and use
action="{{route('GustPosts.update', $DataEdit->id)}}"
#csrf
#method('put')
Form as follows
<form action="{{route('GustPosts.update', $DataEdit->id)}}" method="post">
#csrf
#method('put')
</form>
On Your controllers
Edit Function
public function edit($id)
{
$data = Post::find($id);
return view ('gustUpdateForm',['DataEdit'=> $data]);
}
Update Function
public function update(Request $request, $id)
{
$objProductsUpdate = Post::find($id);
$objProductsUpdate -> ProductName = $request -> get('PNameTxt');
$objProductsUpdate -> ProductModel = $request -> get('PModelTxt');
$objProductsUpdate -> ProductPrice = $request -> get('PPriceTxt');
$objProductsUpdate -> OriginalFileName = $file->getClientOriginalName();
$objProductsUpdate -> FileName = $file->getFilename().'.'.$extension;
$objProductsUpdate ->save();
return redirect()->route('products.index');
}

trying to return items data from invoice

i need to manage invoice items.
here is my code below
in my model i've got this
public function items()
{
return $this->hasMany(invoice_product::class);
}
in the invoice_product model
public function products(){
return $this->belongsTo(prodStock::class);
}
and my controller below is
public function show(invoice $invoice, $id)
{
$invoice = Invoice::with('items.products')->findOrFail($id);
return view('pages.editInvoice', compact('invoice'));
}
Since we are passing variables using compact in the controller, all we have to do is get the view
controller
public function show(invoice $invoice, $id)
{
$invoice = Invoice::with('items.products')->findOrFail($id);
return view('pages.editInvoice', compact('invoice'));
}
view
<select>
#foreach($invoice as $in)
<option value="{{ $in->ColumnName }}">{{ $in->name }}</option>
#endforeach
</select>
If you do like this, you will be able to select in the drop down select

How to display messages received from other users using Laravel

I am working on a messaging functionality on my website between two users and I have managed to make the messaging system work quite alright. But I have a little issue which I can't find a solution to it. I want to be able to show, A list of all message received from other users when the user clicks on this route /conversations. But right now what it does is that it display a list of all users in the users table when I click on the route /conversations which I don't want.
Here are my routes in web
Route::get('/conversations', 'ConversationsController#index')->name('conversations');
Route::get('/conversations/{user}', 'ConversationsController#show')->name('conversations.show');
Route::post('/conversations/{user}', 'ConversationsController#store');
Here is my list of conversations route for index
<div class="contact-edit" id="ci">
<h3>MEssages</h3>
#include('conversations.users', ['users'=>$users, 'unread'=>$unread])
</div>
Here is the conversation.users
<div class="col-md-3">
<div class="list-group">
#foreach($users as $user)
<a class = "list-group-item d-flex justify-content-between align-items-center" href="{{route('conversations.show', $user->id)}}">
{{ $user->name }}
#if(isset($unread[$user->id]))
<span class="badge-pill badge-primary">{{$unread[$user->id]}}</span>
#endif
</a>
#endforeach
</div>
Here is my route opening the conversations tab
Ecrire un message
Here is my conversation controller
class ConversationsController extends Controller
{
private $r;
private $auth;
public function __construct(ConversationRepository $conversationRepository, AuthManager $auth)
{
$this->r = $conversationRepository;
$this->middleware('auth');
$this->auth = $auth;
}
public function index (User $user){
$me = Auth::user();
//dd(Auth::user());
return view('conversations/index', [
'users'=>$this->r->getConversations(Auth::user()->id),
'unread' => $this->r->unreadCount(Auth::user()->id)
]);
}
public function show (User $user){
$me = Auth::user();
$messages = $this->r->getMessagesFor($me->id, $user->id)->paginate(5);
$unread = $this->r->unreadCount($me->id);
if (isset($unread[$user->id])) {
$this->r->readAllFrom($user->id, $me->id);
unset($unread[$user->id]);
}
return view('conversations/show', [
'users'=>$this->r->getConversations($me->id),
'user'=>$user,
'messages'=>$messages,
'unread' => $unread
]);
}
public function store (User $user, StoreMessageRequest $request){
$message = $this->r->createMessage(
$request->get('content'),
Auth::user()->id,
$user->id
);
$user->notify(new MessageReceived($message));
return redirect(route('conversations.show', ['id'=>$user->id]));
}
}
And here is my conversation repository
class ConversationRepository
{
private $user;
private $message;
public function __construct(User $user, Message $message)
{
$this->user = $user;
$this->message = $message;
}
public function getConversations(int $userId)
{
$conversations = $this->user->newQuery()
->select('name','surname','photo','id')
->where('id', '!=', $userId)
->whereType('jobber')
->get();
return $conversations;
}
public function createMessage(string $content, int $from, int $to)
{
return $this->message->newQuery()->create([
'content'=>$content,
'from_id'=>$from,
'to_id'=>$to,
'created_at'=>\Carbon\Carbon::now()
]);
}
public function getMessagesFor(int $from, int $to) : Builder
{
return $this->message->newQuery()
->whereRaw("((from_id = $from AND to_id = $to )OR(from_id = $to AND to_id = $from))")
->orderBy('created_at', 'DESC')
->with([
'from'=> function ($query){ return $query->select('name', 'id');}
]);
}
//Recupere le nombre de message non lu pour chaque conversation
public function unreadCount (int $userId)
{
return $this->message->newQuery()
->where('to_id', $userId)
->groupBy('from_id')
->selectRaw('from_id, COUNT(id) as count')
->whereRaw('read_at IS NULL')
->get()
->pluck('count', 'from_id');
}
THis is my user model
public function messages()
{
return $this->hasMany('App\Message', 'from_id', 'to_id', 'content');
}
This is message model
public function user()
{
return $this->belongsTo('App\User');
}
Any help will be welcome
I'm not sure I am understanding what you want to do but here is a possible solution assuming you want to get all messages that are to you.
In your repository:
$this->message->where('to_id',Auth::user()->id)->get();

Resources