updating data into pivot table - php

i have a many to many realtion and now i wana know how can i update my table with a form that user sends to app . here is my code
route :
Route::get('admin/client/assign','ClientController#assignsellman');
this is my controller
public function assignsellman(Client $client){
$user = User::all();
$client_list = Client::all();
$client = Client::with('sellmanlist')->firstOrFail();
$sellman = $request->input('sellman');
$client_name = $request->input('client');
$client->sellmanlist()->attach($sellman);
$client->sellmanlist()->attach($client_name);
$client->save();
return view('admin.client.assign',compact('client_list','user'));
}
and finnaly the view :
<form action="/admin/client/" method="get">
<input type="hidden" name="_method" value="PUT">
{{ csrf_field() }}
<div class="row">
<div class="col-xs-4">
<div class="form-group">
<label for="client">مشتری</label>
<select class="" tabindex="-1" aria-hidden="true"
name="client">
#foreach($client_list as $client_lists)
<option value="{{$client_lists->id}}">{{$client_lists->title}}</option>
#endforeach
</select>
</div>
</div>
<div class="col-xs-4 text-center">
<i class="icon-arrow-left7 mr-3 icon-3x" style="font-size: 130px"></i>
<h4>ارجاع به</h4>
</div>
<div class="col-xs-4">
<div class="form-group">
<div class="form-group">
<label for="sellman">کارشناس فروش</label>
<select class="" tabindex="-1"
aria-hidden="true" name="sellman">
#foreach($user as $users)
<option value="{{$users->id}}">{{$users->name}}</option>
#endforeach
</select>
</div>
</div>
</div>
</div>
#if ($errors->any())
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
<button type="submit" class="btn btn-primary">تایید</button>
</form>
when i submit this form it redirects to a url like this
?_method=PUT&_token=mvf0i2FaxSBhDdJroqD6L1901QdvcR4b3tmgwekw&client=3&sellman=3
and nothing just happens to database .any idea what is my fault ?

In your case you need 2 routes, first for return form, second to save data from form.
Your routes:
Route::get('admin/client/assign','ClientController#assignsellman');
Route::post('admin/client/assign','ClientController#assignsellmanSave');
Controller:
public function assignsellman(Client $client)
{
$user = User::all();
$client_list = Client::all();
return view('admin.client.assign',compact('client_list','user'));
}
public function assignsellmanSave(Client $client)
{
$user = User::all();
$client_list = Client::all();
$client = Client::with('sellmanlist')->firstOrFail();
$sellman = $request->input('sellman');
$client->sellmanlist()->attach($sellman);
$client->save();
return view('admin.client.assign',compact('client_list','user'));
}
View:
<form action="/admin/client/assign" method="post">
{{ csrf_field() }}
<div class="row">
<div class="col-xs-4">
<div class="form-group">
<label for="client">مشتری</label>
<select class="" tabindex="-1" aria-hidden="true"
name="client">
#foreach($client_list as $client_lists)
<option value="{{$client_lists->id}}">{{$client_lists->title}}</option>
#endforeach
</select>
</div>
</div>
<div class="col-xs-4 text-center">
<i class="icon-arrow-left7 mr-3 icon-3x" style="font-size: 130px"></i>
<h4>ارجاع به</h4>
</div>
<div class="col-xs-4">
<div class="form-group">
<div class="form-group">
<label for="sellman">کارشناس فروش</label>
<select class="" tabindex="-1"
aria-hidden="true" name="sellman">
#foreach($user as $users)
<option value="{{$users->id}}">{{$users->name}}</option>
#endforeach
</select>
</div>
</div>
</div>
</div>
#if ($errors->any())
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
<button type="submit" class="btn btn-primary">تایید</button>
</form>

Related

Laravel 9 "Missing required parameter for [Route:"

I'm using Laravel 9 and trying to use CRUD with my model Project which has the following DB table.
When I try to edit a project using the button "edit" on this view:
"projets.index":
#extends('header')
#section('content')
<div class="col-sm-8" style="background: rgba(204, 204, 204,0.5);padding:5%;width:100%">
<div class="row">
<div class="col-lg-12 margin-tb">
<div class="pull-left">
<h2 style="text-align: center">Les projets</h2>
</div>
<div class="pull-right">
<a class="btn btn-success" href="{{ route('projets.create') }}"> Créée un nouveau projet</a>
</div>
</div>
</div>
#if ($message = Session::get('success'))
<div class="alert alert-success">
<p>{{ $message }}</p>
</div>
#endif
<table class="table table-bordered">
<tr>
<th>id du projet</th>
<th>description</th>
<th width="280px">Action</th>
</tr>
#foreach ($projects as $project)
<tr>
<td>{{ $project->id_project }}</td>
<td>{{ $project->description }}</td>
<td>
<form action="{{ route('projets.destroy',$project->id_project) }}" method="Post">
<a class="btn btn-primary" href="{{ route('galleries.index',$project->id_project,'id_project') }}">ajouter</a>
<a class="btn btn-primary" href="{{ route('projets.edit',[$project->id_project]) }}">Edit</a>
#csrf
#method('DELETE')
<button type="submit" class="btn btn-danger">Delete</button>
</form>
</td>
</tr>
#endforeach
</table>
{!! $projects->links() !!}
</div>
#endsection
I have the following error:
"Missing required parameter for [Route: projets.update] [URI: projets/{projet}] [Missing parameter: projet]."
"projets.edit":
#extends('header')
#section('content')
<div class="row">
<div class="col-lg-12 margin-tb">
<div class="pull-left">
<h2>Edit projet</h2>
</div>
<div class="pull-right">
<a class="btn btn-primary" href="{{ route('projets.index') }}"> Back</a>
</div>
</div>
</div>
#if ($errors->any())
<div class="alert alert-danger">
<strong>Whoops!</strong> There were some problems with your input.<br><br>
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
<form action="{{ route('projets.update',$project->id_project) }}" method="POST" enctype="multipart/form-data">
#csrf
#method('PUT')
<div class="row">
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<strong>Company Address:</strong>
<input type="text" name="address" value="{{ $project->description }}" class="form-control" placeholder="Company Address">
#error('address')
<div class="alert alert-danger mt-1 mb-1">{{ $message }}</div>
#enderror
</div>
</div>
<button type="submit" class="btn btn-primary ml-3">Submit</button>
</div>
</form>
#endsection
Update function inside the controller (ProjectController):
public function update(Request $request, $id_project)
{
$request->validate([
'description' => 'required',
]);
User::create($request->all());
$project->description = $request->description;
$project->save();
return redirect()->route('projets.index')
->with('success','project Has Been updated successfully');
}
public function edit(Project $project)
{
return view('projets.edit',compact('project'));
}
Project model
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Project extends Model
{
protected $fillable = [
'id_project', 'description'
];
}
Sorry if my questions seems strange English is not my first language

Laravel 7: User Profile causing bug when uploading img and bio description

In a laravel 7 app I'm working on a feature where a user can upload their image profile and bio description. A problem that I'm facing is that there are certain cases when a user sets their profile image, the bio description would be gone. For example: If a user set their profile img and puts a description, but if the user sets another img then the description would be gone. Not quite sure what's the bugs that's causing it. (I'm using bootstrap modal for the user to edit their profile.)
controller.php
public function modalEditPost(Request $request)
{
$user = Auth::user();
$avatarName = "";
$userBio = "";
$request->validate([
'bio' => 'nullable|string|max:255',
'image' => 'mimes:jpeg,png,jpg,gif,svg|max:2048',
]);
if ($request->has('bio')) {
$userBio = $request->bio;
$user->bio = $userBio;
}
if ($request->hasFile('image')) {
if ($request->file('image')->isValid()) {
$extension = $request->image->extension();
$avatarName = $user->id.'_avatar'.time().'.'.$extension;
$request->image->move(public_path('/uploads/avatars'), $avatarName);
$user->avatar = $avatarName;
}
}
$user->save();
return back()
->with('success','You have successfully edited your bio.')
->with('bio', $userBio)
->with('image', $avatarName);
}
index.blade.php
#include('partials.popup')
<div class="col-md-4">
<div class="card card-user">
<div class="card-body">
<p class="card-text">
<div class="author">
<div class="block block-one"></div>
<div class="block block-two"></div>
<div class="block block-three"></div>
<div class="block block-four"></div>
<img class = "avatar" src="/uploads/avatars/{{ Auth::user()->avatar}}" alt="">
<h4 class="title">{{ auth()->user()->first_name }} {{ auth()->user()->last_name }}</h5>
</div>
<div class="card-description">
{{ Auth::user()->bio }}
</div>
<br>
<div class="text-center">
<button class="btn btn-success"
style="cursor: pointer"
data-toggle="modal"
data-target="#popupModal">{{ __('Edit Profile') }}
</button>
</div>
</div>
</div>
popup.blade.php
<div class="modal-body">
<!-- (Image upload) Start -->
#if ($message = Session::get('success'))
<div class="alert alert-success alert-block">
<button type="button" class="close" data-dismiss="alert">×</button>
<strong>{{ $message }}</strong>
</div>
#endif
#if (count($errors) > 0)
<div class="alert alert-danger">
<strong>Whoops!</strong> There were some problems with your input.
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
<!-- (Image upload) Start -->
<form action="{{ route('modal.upload.post') }}" method="POST" enctype="multipart/form-data">
#csrf
<div class="row">
<div class="col-md-6">
<input type="file" name="image" class="form-control-file">
</div>
</div>
<br>
<div class="row">
<div class="col">
<p>Change Bio</p>
</div>
</div>
<div class="row">
<div class="col">
<input type="text" style="color:black" name="bio" class="form-control">
</div>
</div>
<br>
<div class="col-md-6">
<button type="submit" class="btn btn-success">Update</button>
</div>
</form>
<!-- (Image upload) End -->
</div>

How can I get a single category of question in a quiz app using Laravel Eloquent

I want to select a single category of questions that the user can select with options. I have tried doing this with a resource I found online.
The category page:
#foreach($categories as $category)
<section>
<a href="#" class="image">
<img src="{{asset('images/pic09.jpg')}}" alt="" data-position="top center" />
</a>
<div class="content">
<div class="inner">
<header class="major">
<h3>{{$category->name}}</h3>
</header>
<p></p>
<ul class="actions">
<li>Learn more</li>
</ul>
</div>
</div>
</section>
#endforeach
Here is the TestController I'm using, the show controller is might to select questions and options with the category_id at random:
namespace App\Http\Controllers;
use App\Category;
use App\Http\Requests\StoreTestRequest;
use App\Option;
class TestsController extends Controller
{
public function show($id)
{
$categories = Category::find($id)->with(
['categoryQuestions' => function ($query) {
$query->inRandomOrder()
->with(
['questionOptions' => function ($query) {
$query->inRandomOrder();
}]
);
}]
)
->whereHas('categoryQuestions')
->get();
return view('client.test', compact('categories'));
}
public function store(StoreTestRequest $request)
{
$options = Option::find(array_values($request->input('questions')));
$result = auth()->user()->userResults()->create(
[
'total_points' => $options->sum('points')
]
);
$questions = $options->mapWithKeys(
function ($option) {
return [$option->question_id => [
'option_id' => $option->id,
'points' => $option->points
]
];
}
)->toArray();
$result->questions()->sync($questions);
return redirect()->route('client.results.show', $result->id);
}
}
web.php
// User
Route::group(['as' => 'client.', 'middleware' => ['auth']], function () {
Route::get('home', 'HomeController#redirect');
Route::get('dashboard', 'HomeController#index')->name('home');
Route::resource('/test', 'TestsController');
Route::get('results/{result_id}', 'ResultsController#show')->name('results.show');
Route::get('send/{result_id}', 'ResultsController#send')->name('results.send');
});
This is the Blade file from the resource I'm using:
#extends('layouts.home')
#section('content')
<div class="container">
<div class="row justify-content-center">
<div class="col-md-8">
<div class="card">
<div class="card-header">Test</div>
<div class="card-body">
#if(session('status'))
<div class="row">
<div class="col-12">
<div class="alert alert-success" role="alert">
{{ session('status') }}
</div>
</div>
</div>
#endif
<form method="POST" action="{{ route('client.test.store') }}">
#csrf
#foreach($categories as $category)
<div class="card mb-3">
<div class="card-header">{{ $category->name }}</div>
<div class="card-body">
#foreach($category->categoryQuestions as $question)
<div class="card #if(!$loop->last)mb-3 #endif">
<div class="card-header">{{ $question->question_text }}</div>
<div class="card-body">
<input type="hidden" name="questions[{{ $question->id }}]" value="">
#foreach($question->questionOptions as $option)
<div class="form-check">
<input class="form-check-input" type="radio" name="questions[{{ $question->id }}]" id="option-{{ $option->id }}" value="{{ $option->id }}"#if(old("questions.$question->id") == $option->id) checked #endif>
<label class="form-check-label" for="option-{{ $option->id }}">
{{ $option->option_text }}
</label>
</div>
#endforeach
#if($errors->has("questions.$question->id"))
<span style="margin-top: .25rem; font-size: 80%; color: #e3342f;" role="alert">
<strong>{{ $errors->first("questions.$question->id") }}</strong>
</span>
#endif
</div>
</div>
#endforeach
</div>
</div>
#endforeach
<div class="form-group row mb-0">
<div class="col-md-6">
<button type="submit" class="btn btn-primary">
Submit
</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
#endsection
How can the Testcontroller be made to select questions and answer from a single category and save the result from the user's answers?
public function index()
{
$questions = Category::select('categories.name', 'question_result.points')
->join('questions', 'categories.id', '=', 'questions.category_id')
->join('question_result', 'questions.id', '=', 'question_result.question_id')
->join('results', 'question_result.result_id', '=', 'results.id')
->where('results.user_id', auth()->id())
->get();
return view('client.home', compact('questions'));
}

Data retrieving issue in Laravel

I'm trying display some data in my blade. Following is my current code for the controller's(ActivateController.php) index function,
public function index($id)
{
//echo $id;
$datas = Website::WHERE('appId','=',$id);
//dd($datas);
return view('activities.index',compact('datas','id'));
}
And my view url is something like,
TEST.site/activities/index/12
this is my blade, index.blade.php
#extends('layouts.admin')
#section('content')
<div class="container">
<div class="row">
<div class="col-sm">
<div class="pull-left">
<h2 class="mt-2">Activate Website</h2>
</div>
<div class="pull-right">
<a class="btn btn-primary" href="{{ route('websites.index') }}"> Back</a>
</div>
</div>
</div>
</div>
#if (count($errors) > 0)
<div class="container ">
<div class="row">
<div class="col-sm">
<div class="alert alert-danger mt-2">
<strong>Whoops!</strong> There were some problems with your input.<br><br>
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
</div>
</div>
</div>
#endif
<div class="container mt-3">
<div class="row">
<div class="col-sm">
#foreach ($datas as $object)
<form id="w1" action="{{ route('activities.update',$object->appId) }}" method="POST">
#csrf
#method('PUT')
<strong>Select Package Type:<span class="star">*</span></strong>
<input type="text" name="app_domain" value="{{$object->domain}}">
<strong>Select Package Type:<span class="star">*</span></strong>
<select id="app-packagetype" class="form-control" name="package_type" aria-required="true">
<option value="{{$object->payment_option }}">{{$object->payment_option }}</option>
<option value="monthly">Monthly [12]</option>
<option value="yearly">Yearly [99]</option>
</select>
<br>
<div class="form-group text-right">
<button type="submit" class="btn btn-success">{{ __('Activate') }}</button>
</div>
</form>
#endforeach
</div>
</div>
</div>
#endsection
But now my issue is , when I try to retrieve the data,
{{$object->appId}}
It retrieves empty....
Where I'm doing wrong and how to retrieve the data properly to the view?
you are missing get() at the end
change this:
$datas = Website::where('appId','=',$id);
to
$datas = Website::where('appId','=',$id)->get();
Thanks..
You use just like this
$datas = Website::where('appId',$id)->get();

Having 2 forms on the same page in Laravel?

I'm trying to tackle a "two forms on one page" issue with my PHP code, but its turning out to be more tirkcy than I expected, and just isn't behaving in the correct way as I thought it would.
For the first form (Login) I'm using this if statement to determine if the message if for the Login.
#if(Session::has('message') && Session::get('last_message_for') == 'login')
<div class="notification is-{{ Session::get('color') }}">
<i class="fa fa-times"></i> {{ Session::get('message') }}
</div>
#elseif($errors->first() && Session::get('last_message_for') == 'login')
<div class="notification is-warning">
<i class="fa fa-times"></i> {{ $errors->first() }}
</div>
#endif
I've got the same code for my second form, but it just checks the last_message_for for a different value to 'login'.
#if(Session::has('message') && Session::get('last_message_for') == 'modal')
<div class="modal is-active" id="modal-forgotPassword">
#else
<div class="modal" id="modal-forgotPassword">
#endif
<div class="modal-background"></div>
<div class="modal-card">
<header class="modal-card-head">
<p class="modal-card-title" id="open-modal">Forgot Password?</p> <button class="delete"></button>
</header>
<form action="{{ route('frontend.guest.password.forgot') }}" method="post">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<section class="modal-card-body">
<div class="content">
#if(Session::has('message') && Session::get('last_message_for') == 'modal')
<div class="notification is-{{ Session::get('color') }}">
<i class="fa fa-times"></i> {{ Session::get('message') }}
</div>
#endif
<div class="field">
<p class="control has-icons-left">
<input class="input" name="email" placeholder="Enter an email..." type="email">
<span class="icon is-small is-left"><i class="fa fa-envelope"></i></span>
</p>
</div>
<input type="hidden" name="_token" value="{{ csrf_token() }}">
</div>
</section>
<footer class="modal-card-foot">
<button class="button is-success" type="submit"><i class="fa fa-sign-in"></i> Send email</button>
</footer>
</form>
</div>
</div>
Now down to the issue, the Login part works perfectly fine and shows the error messages when there are any for it, but the second one isn't showing any errors when I have some.
I'm using this to set the last_message_for
Session::put('last_message_for', 'login');
Here is the code for my second form:
public function onForgotPassword(Request $request) {
$validator = Validator::make($request->all(), [
'email' => 'required|email|exists:users,mail',
]);
Session::put('last_message_for', 'modal');
if ( $validator->fails()) {
return redirect()->route('frontend.guest.login')->withErrors($validator->messages());;
}
else {
Mail::to($request->input('email'))->send(new ForgotPasswordEmail());
return redirect()->route('frontend.guest.login')->withMessage('Email Sent')->withColor('warning');
}
}
You're not handling validation errors, only the messages returned, this should do it.
#if(Session::has('message') && Session::get('last_message_for') == 'modal')
<div class="notification is-{{ Session::get('color') }}">
<i class="fa fa-times"></i> {{ Session::get('message') }}
</div>
#elseif($errors->first() && Session::get('last_message_for') == 'login')
<div class="notification is-warning">
<i class="fa fa-times"></i> {{ $errors->first() }}
</div>
#endif
I have two forms in the same page so you can easily assign it error to each form using flash session
in your controller just use session like this line
use Session;
this code related to two search forms
//searchInHistory
public function searchInHistory(){
$date = Request()->all();
$rules = [
'dateFrom' =>'required',
'dateTo' =>'required',
];
$validator = Validator($date,$rules);
if ($validator->fails()){
Session::flash('inError', 'inError');
return redirect()
->back()
->withErrors($validator)
->withInput();
}else{
$store = DB::table('stores')->select(
'store_details.id',
'store_details.status',
'stores.id AS storeId',
'stores.partNo',
'stores.title',
'store_details.serialNo',
'store_details.created_at',
'store_details.updated_at'
)
->join('store_details', 'store_details.storeId', '=', 'stores.id')
->where('store_details.status','inside')
->whereBetween('store_details.created_at',[$date['dateFrom'],$date['dateTo']])
->get();
return view('crm.store.in',compact('store'));
}
}
//===============
//searchHistory
public function searchOutHistory(){
$date = Request()->all();
$rules = [
'dateFrom' =>'required',
'dateTo' =>'required',
];
$validator = Validator($date,$rules);
if ($validator->fails()){
Session::flash('inError', 'inError');
return redirect()
->back()
->withErrors($validator)
->withInput();
}else{
$store = DB::table('stores')->select(
'store_details.id',
'store_details.status',
'stores.id AS storeId',
'stores.partNo',
'stores.title',
'store_details.serialNo',
'store_details.created_at',
'store_details.updated_at'
)
->join('store_details', 'store_details.storeId', '=', 'stores.id')
->where('store_details.status','outside')
->whereBetween('store_details.updated_at',[$date['dateFrom'],$date['dateTo']])
->get();
return view('crm.store.out',compact('store'));
}
}
//===============
the following code above each error assigned to specific form using session
this is blade code view code related to two form
<!-- Main content -->
<section class="content">
<div class="row">
<div class="col-xs-12">
<div class="box">
<div class="box-header">
<h3 class="box-title">Store IN / OUT Control</h3>
</div>
<div class="row">
<div class="col-md-6">
<div class="box-body">
#if(session('outError'))
#if ($errors->any())
<div class="alert alert-danger">
<center>
#foreach ($errors->all() as $error)
{{ $error }}<br>
#endforeach
</center>
</div>
#endif
#endif
#if(session('out'))
#if(session('save'))
<div class="alert alert-success">
<center>
Products Came out of Successfully
</center>
</div>
#endif
#endif
<!-- form start -->
<form role="form" method="post" action="{{url('admin/takeProductOutStore')}}" enctype="multipart/form-data">
{{csrf_field()}}
<div class="box-body">
<input type="hidden" name="id" value="{{$storeId}}">
<div class="form-group">
<label>Products in Store</label>
<select multiple class="form-control" name="products[]" required>
#foreach($InDoorProducts as $row)
<option value="{{$row->serialNo}}">{{$row->serialNo}}</option>
#endforeach
</select>
</div>
<div class="form-group">
<label>Date</label>
<input type="date" class="form-control" name="date" required>
</div>
<div class="form-group">
<textarea class="textarea" required placeholder=" Write Notes"style="width: 100%; height: 125px; font-size: 14px; line-height: 18px; border: 1px solid #dddddd; padding: 10px;" name="note" value="{{old('note')}}"></textarea>
</div>
</div><!-- /.box-body -->
<div class="box-footer">
<button type="submit" class="btn btn-primary">Out Store <b>→</b></button>
</div>
</form>
</div>
</div>
<div class="col-md-6">
<div class="box-body">
#if(session('inError'))
#if ($errors->any())
<div class="alert alert-danger">
<center>
#foreach ($errors->all() as $error)
{{ $error }}<br>
#endforeach
</center>
</div>
#endif
#endif
#if(session('in'))
#if(session('save'))
<div class="alert alert-success">
<center>
Products Added to Store Again Successfully
</center>
</div>
#endif
#endif
<!-- form start -->
<form role="form" method="post" action="{{url('admin/takeProductInStore')}}" enctype="multipart/form-data">
{{csrf_field()}}
<div class="box-body">
<input type="hidden" name="id" value="{{$storeId}}">
<div class="form-group">
<label>Products Out Store</label>
<select multiple class="form-control" name="products[]" required>
#foreach($OutDoorProducts as $row)
<option>{{$row->serialNo}}</option>
#endforeach
</select>
</div>
<div class="form-group">
<label>Date</label>
<input type="date" class="form-control" name="date" required>
</div>
<div class="form-group">
<textarea class="textarea" required placeholder=" Write Notes"style="width: 100%; height: 125px; font-size: 14px; line-height: 18px; border: 1px solid #dddddd; padding: 10px;" name="note" value="{{old('note')}}"></textarea>
</div>
</div><!-- /.box-body -->
<div class="box-footer">
<button type="submit" class="btn btn-primary">Back To Store <b>←</b></button>
</div>
</form>
</div>
</div>
</div>
</section>

Categories