I'm trying to increment a variable and pass it to my Controller.
When i click the Button1 the variable is incremented on every click.
When i click the Button2 the variable is only incremented on every second click.
this is my livewire view:
<div style="text-align: center">
<button wire:click="incrementMastery">Button1</button>
<h1>{{ $count }}</h1>
</div>
<form method="POST" action="{{ route('books.index') }}" wire:submit="incrementMastery">
<input type="hidden" wire:model="count" name="count" value="{{$count}}">
#csrf
<button type="submit">{{ __('Button2') }}</button>
</form>
this is my livewire component:
<?php
namespace App\Http\Livewire;
use Livewire\Component;
use Illuminate\Support\Facades\Log;
class Mastery extends Component
{
public $count = 0;
public function mount()
{
$this->count = session('count', 0);
}
public function incrementMastery()
{
$this->count++;
Log::debug($this->count);
session(['count' => $this->count]);
$this->emit('submit');
return redirect()->route('books.index', ['mastery' => $this->count]);
}
public function render()
{
return view('livewire.mastery', ['count' => $this->count]);
}
}
this is my controller:
public function index(Request $request)
{
$mastery = $request->input('mastery');
return view('books.index', ['mastery' => $mastery]);
}
and that is the log (clicking Button2):
[2023-02-04 10:13:18] local.DEBUG: 11
[2023-02-04 10:13:26] local.DEBUG: 11
[2023-02-04 10:13:27] local.DEBUG: 12
[2023-02-04 10:13:28] local.DEBUG: 12
[2023-02-04 10:13:29] local.DEBUG: 13
[2023-02-04 10:13:30] local.DEBUG: 13
[2023-02-04 10:13:30] local.DEBUG: 14
[2023-02-04 10:13:36] local.DEBUG: 14
Related
I have many to many relationship between UserProfile model and UserTv model. Here are the tables.
user_profiles
id user_id username
1 1 AuthUser
tv
id name
1 Action
2 Drama
3 Comedy
4 manually added some genre from input from authenticated user
user_tv
id user_id tv_id
1 1 2
1 1 4
For example, these first three ids in tv table (Action, Drama, Comedy) are inserted through seeders and this fourth id is inserted manually through input text from form by that user who is authenticated. And there lies the my problem. I want that those values that are manually added through input in form to only be able to see that user that inserted those values, and all other users can't. But also I want all users to remain to see those first three values that are generated through seeder. Currently everything works so that all users can see everything. Any help is appreciated. Here is my code.
UserProfile.php
<?php
namespace App;
use App\User;
use Illuminate\Support\Facades\App;
use Illuminate\Database\Eloquent\Model;
class UserProfile extends Model
{
protected $fillable = [
'user_id',
'username',
];
public function user()
{
return $this->belongsTo(User::class);
}
public function tvs()
{
return $this->belongsToMany(UserTv::class, 'user_tv', 'user_id', 'tv_id');
}
}
UserTv.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class UserTv extends Model
{
protected $table = 'tv';
protected $fillable = [
'name'
];
public function userProfiles()
{
return $this->belongsToMany(UserProfile::class, 'user_tv', 'tv_id', 'user_id');
}
}
web.php
Route::get('profile/{profile}', 'UserProfileController#showProfile')->name('profile.show');
Route::patch('profile/update-tv-options', 'TvController#updateTvOptions')->name('profile.update.tv.options');
Route::post('profile/insert-tv-options', 'TvController#insertTvOptions')->name('profile.insert.tv.options');
TvController.php
<?php
namespace App\Http\Controllers;
use App\UserTv;
use App\UserProfile;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Auth;
use App\Http\Requests\InsertTvOptionsRequest;
use App\Http\Requests\UpdateTvOptionsRequest;
class TvController extends Controller
{
public function updateTvOptions(UpdateTvOptionsRequest $request)
{
$user = Auth::user();
$userProfile = UserProfile::where('user_id', Auth::id())->first();
$userProfile->update($request->all());
$data = $request->get('tvsOptions', '[]');
$userProfile->tvs()->sync($data);
return redirect()->route('profile.show', [$user->username]);
}
public function insertTvOptions(InsertTvOptionsRequest $request)
{
$user = Auth::user();
$tv = UserTv::create($request->all());
return redirect()->route('profile.show', [$user->username]);
}
}
UserProfileController.php
<?php
namespace App\Http\Controllers;
use App\User;
use App\UserTv;
use App\UserProfile;
class UserProfileController extends Controller
{
public function showProfile($username, Request $request)
{
$profileId = User::getIdFromUsername($username);
$userForShowProfile = User::with('userProfile')->where('id', $profileId)->firstOrFail();
$tvsOptions = UserTv::get();
$userTvsOptions = UserProfile::findOrFail($profileId)->tvs()->get();
return view('profile.show', compact('userForShowProfile', 'tvsOptions', 'userTvsOptions'));
}
}
show.blade.php
<section data-edit="movies" class="editMovies">
<h3 class="textBold">Film</h3>
<form action="{{ route('profile.update.tv.options') }}" method="POST" class="flex">
#method('PATCH')
#csrf
<div class="form-group flex">
#isset($tvsOptions, $userTvsOptions)
#foreach($tvsOptions as $option)
<div class="interestedIn">
<input type="checkbox" name="tvsOptions[]" value="{{ $option->id }}" {{ $userTvsOptions->contains('id', $option->id)? 'checked': ''}}>
<label for="">{{ $option->name }}</label>
</div>
#endforeach
#endisset
</div>
<div class="form-group">
<label for="" class="textBold">Button FOR CHECKBOX</label>
<input type="submit" class="form-control" name="submit" value="BUTTON">
</div>
</form>
<form action="{{ route('profile.insert.tv.options') }}" method="POST" class="flex">
#csrf
<div class="form-group mt-5">
<input type="text" name="name" placeholder="INSERT NEW MOVIE GENRE">
</div>
<div class="form-group">
<label for="" class="textBold">Button FOR INSERT!!!</label>
<input type="submit" class="form-control" name="submit" value="BUTTON">
</div>
</form>
</section>
And I want to contain first three options for all users and that fourth option for only this user that inserted that.
Something like this?
$defaultTvsOptions = UserTv::whereIn('name', ['Action', 'Drama', 'Comedy'])->get(); // return only action, drama and comedy. you can use ids.
$userTvsOptions = UserProfile::findOrFail($profileId)->tvs;
$tvsOptions = $defaultTvsOptions->merge($userTvsOptions); // merge default and logged user tvs options
To make it more maintainable, you could use configs in your root directory of project.
$defaultTvsOptions = UserTv::whereIn('name', config('config name where return the array'));
Hope it helps you.
Hey As you Have a pivot table You can pull the data Like This:
Userprofile model
public function tv() {
return $this->hasManyThrough(
'Tv class ',
'user_tv class',
'user_id',
'id',
'user_id',
'tv_id'
);
}
UserController
$data = UserProfile::with('tv')
->where(condition)
->get();
I'm learning Laravel and I got stuck trying to get data from a form.
I already am able to get data back with GET, but with POST I've been having a ton of trouble. Here's what I'm working with:
Form:
<form id="forms" method="POST" action="sugestoes" novalidate>
{{ csrf_field() }}
<div class="form-row">
<div class="form-group col-md-12">
<label for="obs">Observações:</label>
<textarea type="text" class="form-control" name="obs" placeholder="Observações" required></textarea>
</div>
</div>
<hr>
<button type="submit" class="btn btn-primary">Enviar</button>
</form>
#php
if (isset($_POST["obs"])) {
echo "IN";
}
#endphp
Controller:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class PostController extends Controller
{
public function store(Request $request)
{
$name = $request->input('obs');
return redirect('sugestoes');
//
}
}
Route:
Route::post('sugestoes', 'PostController#store');
The intended behaviour that I'm trying to reach is for the post to be submitted, and then returning to the same page with an empty form. Later on I'll be sending the input data into a database, but for now I just want to get the post to work.
I guess I'm missing something really basic, but I've been following guides and looking online, I've done some progress but I'm really stuck here.
(some more info, this is Laravel 5.4, and I'm using XAMPP)
First, you need to call the model, use App/Your_model_name; then you have to save the data.
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Suggest; //Suggest model, let's hope you have suggest table
class PostController extends Controller
{
public function store(Request $request)
{
$suggest = new Suggest; //model
$suggest->name = $request->obs; //name is DB name, obs is request name
$suggest->save(); //save the post to DB
return redirect()->back()->with('success', 'Saved successfully'); //return back with message
}
}
Then if you want to flash the message on the HTML page
#if(session('success'))
<div class="alert alert-warning alert-dismissible" id="error-alert">
<strong style="color: white;">{{session('success')}}</strong>
</div>
#endif
<form id="forms" method="POST" action="{{ route('sugestoes') }}" novalidate>
{{ csrf_field() }}
<div class="form-row">
<div class="form-group col-md-12">
<label for="obs">Observações:</label>
<textarea type="text" class="form-control" name="obs" placeholder="Observações" required></textarea>
</div>
</div>
<button type="submit" class="btn btn-primary">Enviar</button>
</form>
Remove the #php tag below the form, then in router.php
Route::post('/sugestoes', 'PostController#store')->name('sugestoes');
Then in Controller:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class PostController extends Controller
{
public function store(Request $request)
{
$name = $request->input('obs');
return redirect('/sugestoes'); // you should have GET in Route.php
//
}
}
Add the following code in your action attribute on the form. It will capture the post URL. When you submit the form it will send the form data to the URL end-point.
action="{{ url('sugestoes')}}"
Then die and dump in your controller store function
public function store(Request $request)
{
dd($request->all());
}
I created a modal which displays information specific to their id entries and placed the Approve and Reject button as below.
Screenshot of modal
When a user click on "Accept" or "Reject", it needs to pass id related to the viewed entries so the user can perform the requested action, whether to accept or reject the entries (default status is 'pending').
vendor.blade.php
<div class="modal-footer">
<span class="pull-left">
<form method="POST" action="{{ route('approve') }}">
#method('PUT')
#csrf
<button type="submit" class="btn btn-success">Approve</button>
</form>
</span>
<span class="pull-right">
<form method="POST" action="{{ route('reject') }}">
#method('PUT')
#csrf
<button type="submit" class="btn btn-danger">Reject</button>
</form>
</span>
</div>
In VendorController.php
public function index()
{
$vendors = DB::select('select company_name, roc_no, created_at from mides_vendors');
$vendor_id = Vendor::where('status', 'Pending');
return view('panel.vendor', ['vendors' => $vendors]);
}
ApprovedVendorController.php
<?php
namespace App\Http\Controllers;
use App\User;
use App\Vendor;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
class ApproveVendorController extends Controller
{
public function approve(Request $request, $id)
{
DB::insert('insert into mides_users(name, email, password) select name,roc_no,password from mides_vendors where id = :id', ['id' => $id]);
DB::update('update mides_vendors set status = :status where id = :id', ['status' => 'Approved', 'id' => $id]);
return redirect('/');
}
public function reject(Request $request, $id)
{
DB::update('update mides_vendors set status = :status where id = :id', ['status' => 'Rejected', 'id' => $id]);
return redirect('/');
}
}
routes/web.php
Route::prefix('/panel')->group(function () {
Route::get('/dashboard', function () {
return view('panel.dashboard');
});
/* These routes only display the information/modal
Route::get('/approve-vendor', 'VendorController#showNewRegistration'); // return vendor.blade.php
Route::get('/vendor-approved', 'VendorController#showApproved'); // return vendor-approve.blade.php
Route::get('/vendor-reject', 'VendorController#showRejected'); // return vendor-reject.blade.php
/* These route used to perform the specific action */
Route::put('/approve/{id}', 'ApproveVendorController#approve')->name('approve');
Route::put('/reject{id}', 'ApproveVendorController#reject')->name('reject');
});
However, it returns this error.
Error got after clicking Accept or Reject
How do I pass the id of data? I tried as shown in pass the database value to modal popup to create the modal using second answer option (besides the ajax ones). Do I need to create another controller for these?
Edited: after do as explained by #Wreigh, it works, means that the status changed from 'pending' to 'accept/reject'. But, when I return to the previous page, which is the /panel/approve-vendor (the page is used for showing the pending list modal) then I got the error undefined variable vendorId.
You can provide the id via the url, or you can also use post values. However, let's try via the url as a parameter.
Update your routes to be like these:
Route::put('/approve/{id}', 'ApproveVendorController#approve')->name('approve');
Route::put('/reject/{id}', 'ApproveVendorController#reject')->name('reject');
Then in your form:
<form method="POST" action="{{ route('approve', $vendorId) }}">
<form method="POST" action="{{ route('reject', $vendorId) }}">
If you want via post values.
There's no need to update your routes, but update your controller action signatures:
public function approve(Request $request) {
$id = $request->input('id');
}
public function reject(Request $request) {
$id = $request->input('id');
}
And then insert this in your form:
<input type="hidden" name="id" value="{{ $vendorId }}">
WHY DO YOU ENCOUNTER THE ERROR?
In your function signature, you are expecting an $id parameter, which in your route definition, you do not have. Laravel cannot provide it magically like that, you have to provide it via the url, as a parameter.
since your approve route is like this /approve/{id} you cannot go to panel/approve because your are not passing the id
so try this:
vendor.blade.php (remove put and your id as hidden input)
<div class="modal-footer">
<span class="pull-left">
<form method="POST" action="{{ route('approve') }}">
<input type="hidden" name="id" value="{{ $id}}">
#csrf
<button type="submit" class="btn btn-success">Approve</button>
</form>
</span>
<span class="pull-right">
<form method="POST" action="{{ route('reject') }}">
#csrf
<input type="hidden" name="id" value="{{ $id}}">
<button type="submit" class="btn btn-danger">Reject</button>
</form>
</span>
</div>
ApprovedVendorController.php (remove all the parameters)
<?php
namespace App\Http\Controllers;
use App\User;
use App\Vendor;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
class ApproveVendorController extends Controller
{
public function approve()
{
$id = request('id');
DB::insert('insert into mides_users(name, email, password) select name,roc_no,password from mides_vendors where id = :id', ['id' => $id]);
DB::update('update mides_vendors set status = :status where id = :id', ['status' => 'Approved', 'id' => $id]);
return redirect('/');
}
public function reject()
{
$id = request('id');
DB::update('update mides_vendors set status = :status where id = :id', ['status' => 'Rejected', 'id' => $id]);
return redirect('/');
}
}
routes/web.php (remove parameters)
Route::prefix('/panel')->group(function () {
Route::get('/dashboard', function () {
return view('panel.dashboard');
});
/* These routes only display the information/modal
Route::get('/approve-vendor', 'VendorController#showNewRegistration'); // return vendor.blade.php
Route::get('/vendor-approved', 'VendorController#showApproved'); // return vendor-approve.blade.php
Route::get('/vendor-reject', 'VendorController#showRejected'); // return vendor-reject.blade.php
/* These route used to perform the specific action */
Route::put('/approve', 'ApproveVendorController#approve')->name('approve');
Route::put('/reject', 'ApproveVendorController#reject')->name('reject');
});
I have problem to save name and email from user1 in table user1s that I have made .
When I enter them in textareas using html form in Laravel with route::post and function store it is not working. When I enter text and hit the button Register it outputs the following error:
MethodNotAllowedHttpException in RouteCollection.php line
You will see that I use the HTML form and that I have tried to add <input ....> into my form.
Here are my files:
route.php
<?php
Route::get('/','PageController#home');
Route::post('/','User1Controller#store');
Route::get('about','PageController#about');
welcome.blade.php
I'm not sure about the action.
After putting user1 inf into table, it should be redirected to a "Thank you" page (I have a thankyou.blade.php ) , maybe that is the problem
<form method="POST" action="">
<input name="_token" type="hidden" value="{{ csrf_token() }}"/>
<ul class="list-group" >
<li >
NAme
<div class="form-group" title="email" >
<textarea name="name" class="form-control" >
</textarea>
</div>
</li >
<li>Email
<div class="form-group" >
<textarea name="email" class="form-control" >
</textarea>
</div>
</li>
<li >
<div class="form-group" >
<button class="btn btn-primary">Register</button>
</div>
</li>
</ul>
</form>
migration for user1
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateNotesTable extends Migration
{
public function up()
{
Schema::create('notes', function (Blueprint $table) {
$table->increments('id');
$table->integer('card_id')->unsigned();
$table->text('body');
$table->timestamps();
});
}
public function down()
{
Schema::drop('notes');
}
}
user1controller.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\User1;
class User1Controller extends Controller
{
public function store(Request $request)
{
$user= new User1;
$user->name = $request->name;
$user->email = $request->email;
$user->save();
return view('thankyou');
}
}
pagecontroller.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\User1;
class PageController extends Controller
{
public function home()
{
$user1s= User1::all();
return view('welcome',compact('user1s'));
}
public function about()
{
return view('pages.about');
}
}
Your form is basically a registration form. I would recommend using a more meaningful name for the end point. The post route can be something like,
Route::post('/register','User1Controller#store');
Now the form action can be,
action="/register"
I corrected the typo.Thanks!
I have also changed this
Route::post('/','User1Controller#store');
and action=" " .
It works ,the only thing right now that is not good is that I should redirect to a page "Thank you" not go to anther view on the exact same page.
Because It makes a mess in the database when I reload the home page.
I'll try that and tell if it works.
Thank you people for the help! :)
Things solved,this works. I will add the code that i have added so the other can find it!
Firs of all : I haven't figured why ,but action="dir1/dir3" for me didn't work!
Here are the added things!
routes.php
Route::get('thankyou','PageController#thankyou');
***PageController.php***
public function thankyou()
{
return view('thankyou');
}
*****User1Controller.php*****
public function store(Request $request)
{
$user= new User1;
$user->name = $request->name;
$user->email = $request->email;
$user->save();
return redirect('/thankyou');
}
i'm new in Laravel 5 framework. I make a form. In the form, I create one button to search inventory codes and then fill the text input in the form. The Controllers are work well. But, when I try return view('cari'), the browser doesn't show up anything. These is my codes:
in Controller:
public function search(){
echo "212";
return view('cari');
}
The index method in my controller works well.
public function checkAction()
{
if(Input::get('submit')) {
$this->create();
} else if(Input::get('cari')) {
$this->search();
}
}
Then, I try another way use return redirect('cari'); in my controller with no display anything.
If I edit my post in routes.php and directly call myController#search it does display the cari.blade.php. But, I want from the search form trigger to browse inventory items. Could you give me some clues?.
This is my permintaan.blade.php which i created a button to checkAction():
<form class="form-horizontal" role="form" method="POST" action="{{ url('/permintaan') }}">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<div class="form-group">
<label class="col-md-4 control-label">Kode Inventaris</label>
<div class="col-md-6">
<input type="text" class="form-control" name="kodeInventaris" value="{{ old('kdInventaris') }}">
</div>
<button type="submit" class="btn btn-primary" name="cari" value="cari">
Cari
</button>
</div>
....
</form>
These is my create and store functions:
public function create(Request $request)
{
$data = $request->except('_token');
$validator = $this->validator($data);
if ($validator->fails())
{
$this->throwValidationException(
$request, $validator
);
}
$this->store($data);
$request->find($request);
return redirect()->back()->with('message', 'Permintaan berhasil diinput');
}
public function store(array $data){
Permintaan::create([
'kdInventaris' => $data['kodeInventaris'],
'namaInventaris' => $data['namaInventaris'],
'jenis' => $data['optInventaris'],
'jumlah' => $data['jumlah'],
'spesifikasi' => $data['spesifikasi'],
'keterangan' => $data['keterangan'],
]);
}
when redirect. It works, but got a blank page again. and replace with echo.
It works, but has this message and got a successful redirect:
"HTTP/1.0 302 Found Cache-Control: no-cache Date: Mon, 01 Jun 2015 16:04:33 GMT Location: http://localhost:8000/permintaan Redirecting to http://localhost:8000/permintaan."
I wonder with my return redirect()->back()->with('message', 'Permintaan berhasil diinput');
You're doing the operation and not returning any view in your controller
You can do it by
public function checkAction()
{
if(Input::get('submit')) {
$this->create();
return view('cari')->with('message', 'Succesfully created');
} else if(Input::get('cari')) {
$this->search();
return view('cari')->with('message', 'Search Done');
}
}
Note :
I dont know any of your view name so i am using the same name cari you can replace it with any view that you have.