Unable to store in database while using Laravel (version 7.25) - php

I am trying to get hold of Laravel framework and got stuck while retrieving the values from the page in a Database.
These are the snippets of my controller, routes, view part which might help in understanding what I am doing
web.php (for routes):
<?php
use Illuminate\Support\Facades\Route;
Route::resource('posts', 'PostController');
Postcontroller.php (just a snippet)
<?php
public function create()
{
//
return view('posts.create');
}
public function store(Request $request)
{
//
$this->validate($request , array(
'title' => 'required',
'body' => 'required'
));
$post = new Post;
$post->title = $request->title;
$post->body = $request->body;
$post->save();
return redirect()->route('posts.show', $post->id);
}
create.blade.php(for view)
<div class="row">
<div class="col-mid-8 col-md-offset-2" >
<h1>Create New Post</h1>
<hr>
<form route='posts.store' >
#csrf
<div class="form-group">
<label for="exampleInputEmail1">Email address</label>
<input type="email" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp">
<small id="emailHelp" class="form-text text-muted">We'll never share your email with anyone else.</small>
</div>
<div class="form-group">
<label for="exampleInputPassword1">Password</label>
<input type="password" class="form-control" id="exampleInputPassword1">
</div>
<div class="form-group form-check">
<input type="checkbox" class="form-check-input" id="exampleCheck1">
<label class="form-check-label" for="exampleCheck1">Check me out</label>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</div>
</div>

The problem with your code is that you don't have name properties on your input, so nothing gets passed to your backend code.
Add name to your inputs like this (they need to be different, else they would get overwritten):
<input type="text" class="form-control" id="your-unique-input-id" name"your_unique_input_name">
Then, when you submit your form, the all the inputs that have name attribute in them will get passed to your backend method. You can then retrieve their value, by using the name you gave them earlier. So in this example:
$request->your_unique_input_name // Which will return anything that user typed in that field

Related

Request contains null although the input has been entered

I'm trying to update my data with Laravel. I'm able to create, read, delete the data but somehow i cannot update my data. I already checked my controller,model,route and view but i don't think there's any typo or anything. It only redirects to it's index page without being updated although i have entered new input. There's no error message at all so i checked where is the problem. So i checked my update function in my controller and tried to show the request by echo "$request->kode_kontak"; and echo $request->kode_kontak; but it shows nothing which i assume that it's null/empty but when i echo "yes" it showed on the screen "yes" i tested this because i want to know if the function itself is working so the problem here is that the request contains null, no wonder i cannot update it. Why is the request isn't passed? why is it like this? and how to fix it?
Route for edit and update
Route::get('contact/{contact}/edit', 'ContactController#edit')->name('contact.edit');
Route::patch('contact/{contact}','ContactController#update')->name('contact.update');
Controller with edit and update function
use Illuminate\Http\Request;
use App\Contact;
use DB;
public function edit($kode_kontak){
$contact = DB::table('contact')->where('kode_kontak',$kode_kontak)->get();
return view('contact.edit',['contact' => $contact]);
}
public function update(Request $request){
DB::table('contact')->where('kode_kontak',$request->kode_kontak)->update([
'email' => $request->email,
'telepon' => $request->telepon,
]);
return redirect('contact');
}
Model
class Contact extends Model
{
public $timestamps = false;
protected $table = 'contact';
protected $fillable = [
'kode_kontak',
'kode_pegawai',
'email',
'telepon'
];
protected $primaryKey = 'kode_kontak';
}
View of edit.blade.php
<div id="contact">
<h2>Edit Contact</h2>
#foreach($contact as $p)
<form action="{{ route('contact.update', ['kode_pegawai' => $p->kode_pegawai]) }}" method="POST">
#csrf
#method('patch')
<div class="form-group">
<label for="kode_contact" class="control-label">Kode Kontak</label>
<input type="text" name="kode_kontak" id="kode_kontak" class="form-control" value="{{ $p->kode_kontak}}" disabled>
</div>
<div class="form-group">
<label for="kode_pegawai" class="control-label">Kode Pegawai</label>
<input type="text" name="kode_pegawai" id="kode_pegawai" class="form-control" value="{{ $p->kode_pegawai}}" disabled>
</div>
<div class="form-group">
<label for="email" class="control-label">Email</label>
<input type="text" name="email" id="email" class="form-control" value="{{ $p->email}}">
</div>
<div class="form-group">
<label for="telepon" class="control-label">Telepon</label>
<input type="text" name="telepon" id="telepon" class="form-control" value="{{ $p->telepon}}">
</div>
<div class="form-group">
<input class="btn btn-primary form-control" type="submit" value="Simpan">
</div>
</form>
#endforeach
</div>
Your issue is that you have disabled those inputs. Disabled inputs will not be submitted.
If you want to display the disabled inputs, but still PATCH the values, you will need to add hidden inputs with those values like:
<div class="form-group">
<label for="kode_contact" class="control-label">Kode Kontak</label>
<input type="text" id="kode_kontak" class="form-control" value="{{ $p->kode_kontak}}" disabled>
<input type="hidden" name="kode_kontak" value="{{ $p->kode_kontak}}">
</div>
<div class="form-group">
<label for="kode_pegawai" class="control-label">Kode Pegawai</label>
<input type="text" id="kode_pegawai" class="form-control" value="{{ $p->kode_pegawai}}" disabled>
<input type="hidden" name="kode_pegawai" value="{{ $p->kode_pegawai}}">
</div>
Hope that helps!
$request->kode_kontak is $contact here, $request->kode_kontak is not available in $request, change $contact instead :
public function update(Request $request, $contact){
DB::table('contact')->where('kode_kontak',$contact)->update([
'email' => $request->email,
'telepon' => $request->telepon,
]);
return redirect('contact');
}

POST request is not tallied with the form in Laravel Blade

I am a newbie in Laravel.
My problem is, when I tried to update my form, it kept saying that the tablename not found eventhough I already mentioned it inside my Model. But when I debugged, I found that the request is not the same from what I put inside my form.
But my form actually doesn't have that.
Any idea how this is happening, guys? Pretty sure I missed something but unsure what is it.
Event Model
class Event extends Model
{
//
protected $fillable = ['title', 'objective', 'date', 'venue', 'description', 'slug'];
public function getRouteKeyName()
{
return 'slug';
}
}
Event Controller
class EventController extends Controller
{
public function update(Request $request, Event $event)
{
//
$validated = $request->validate([
'title' => 'required|string|unique:event|min:5|max:100',
'objective' => 'required|string|min:5|max:2000',
'date' => 'required|string|min:5|max:2000',
'venue' => 'required|string|min:5|max:2000',
'description' => 'required|string|min:5|max:2000'
]);
// Create slug from title
$validated['slug'] = Str::slug($validated['title'], '-');
// Update Post with validated data
$event->update($validated);
// Redirect the user to the created post woth an updated notification
return redirect(route('events.edit', [$event->slug]))->with('notification', 'Event updated!');
}
Edit Blade Page
<form method="post" action="{{ route('events.update', [$event->slug]) }}">
#csrf
#method('patch')
#include('partials.errors')
<div class="field">
<label class="label">Title</label>
<div class="control">
<input type="text" name="title" value="{{ $event->title }}" class="input" placeholder="Title" minlength="5" maxlength="100" required />
</div>
</div>
<div class="field">
<label class="label">Objective</label>
<div class="control">
<textarea name="content" class="textarea" placeholder="Content" minlength="5" maxlength="2000" required rows="10">{{ $event->objective }}</textarea>
</div>
</div>
<div class="field">
<label class="label">Date</label>
<div class="control">
<input type="text" name="title" value="{{ $event->date }}" class="input" placeholder="Title" minlength="5" maxlength="100" required />
</div>
</div>
<div class="field">
<label class="label">Venue</label>
<div class="control">
<input type="text" name="title" value="{{ $event->venue }}" class="input" placeholder="Title" minlength="5" maxlength="100" required />
</div>
</div>
<div class="field">
<label class="label">Description</label>
<div class="control">
<textarea name="content" class="textarea" placeholder="Content" minlength="5" maxlength="2000" required rows="10">{{ $event->description }}</textarea>
</div>
</div>
<div class="field">
<div class="control">
<button type="submit" class="button is-link is-outlined">Update</button>
</div>
</div>
</form>
Thank you for your time!
You need to change the name attribute of Date, Venue and Description and Objective.
On your edit blade page, the input names are alternating 'title' and 'content'
can you rename the input names so that they can be unique

How to show and edit same blade in laravel?

I have a user and profile table and user_id is the foreign key in the profile table and oneto one relationship. Now I am trying to show the data of user and profile in text field at the profile blade. Also, I want to save edit data in using same text field by clicking save change button. I can showing the user table data using value="{{Auth::user()->mobile}}" but confused to show profile data and how to edit user and profile data. How can I edit the all data?
Profile Blade
<div class="tab-pane active" id="tab_1_1">
<form role="form" method="POST">
{{ csrf_field() }}
<div class="form-group">
<label class="control-label">Full Name</label>
<input type="text" value="{{Auth::user()->name}}" name="name" class="form-control">
</div>
<div class="form-group">
<label class="control-label">Email</label>
<input type="text" value="{{Auth::user()->email}}" name="email" class="form-control"> </div>
<div class="form-group">
<label class="control-label">Mobile Number</label>
<input type="text" value="{{Auth::user()->mobile}}" name="mobile" class="form-control">
</div>
<div class="form-group">
<label class="control-label">Organization</label>
<input type="text" value="" name="organization" class="form-control">
</div>
<div class="form-group">
<label class="control-label">Department</label>
<input type="text" value="" name="department" class="form-control">
</div>
<div class="form-group">
<label class="control-label">Designation</label>
<input type="text" value="" name="designation" class="form-control">
</div>
<div class="form-group">
<label class="control-label">Address</label>
<textarea class="form-control" rows="3" name="address" value=""></textarea>
</div>
<div class="margiv-top-10">
#if (Auth::user()->id)
<!-- <button type="submit" class="btn btn-primary">Edit</button> -->
Save
#endif
Cancel
</div>
</form>
</div>
Controller
public function profileDataUpdate(Request $request)
{
$this->validate($request,[
'user_id'=> '',
'organization' => '',
'department' => '',
'designation' => '',
'address' => '',
]);
$users = new User();
$users->name = $request->name;
$users->email = $request->email;
$users->mobile = $request->mobile;
$users->save();
$profiles = new Profile();
dd($profiles->user_id = $request->user_id);
$profiles->organization = $request->organization;
$profiles->department = $request->department;
$profiles->designation = $request->designation;
$profiles->address = $request->address;
$profiles->save();
return redirect(route('profile'))->with('successMsg','profile Successfully Updated');
}
First, you need to fetch user information in controller, with that way you show related information easly
in your user model
user model
public function profile(){
return $this->hasOne(Profile::class,"user_id","id");
}
in your controller (we gonna fetch user information)
public function showProfile(){
$id = Auth::id();
$user = User::with("profile")->find($id);
return view("profile",compact("user"));
}
view (so in your view, we're able to get profile information with $user variable)
name: {{$user->name}}
organization: {{$user->profile->organization}}
And updating.. You're not updating in your controller, you're trying to create new user and profile.
I assume that profile informations doesn't exist at the first, so we need to use updateOrCreate method
public function profileDataUpdate(Request $request)
{
// validation stuff here
User::where("id", $request->user_id)
->update([
"name" => $request->name,
"email" => $request->email,
"mobile" => $request->mobile
]);
Profile::updateOrCreate(["user_id" => $request->user_id],[
"organization" => $request->organization,
"department" => $request->department,
"designation" => $request->designation,
"address" => $request->address,
]);
return redirect(route('profile'))->with('successMsg','profile Successfully Updated');
}

Form data is not submitting into database using laravel 5.4 version

I am trying to simply adding my form data but i dont know where i am wrong my html view:
<form action="{{url('add/talent')}}" method="post" role="form">
{!! csrf_field() !!}
<div class="row">
<div class="col-xs-4 col-sm-4 col-md-4 col-lg-4">
<div class="form-group">
<label for="">First Name</label>
<input type="text" name="first_name" class="form-control" id="" placeholder="">
</div>
</div>
<div class="col-xs-4 col-sm-4 col-md-4 col-lg-4">
<div class="form-group">
<label for="">Middle Name</label>
<input type="text"name="middle_name" class="form-control" id="" placeholder="">
</div>
</div>
<div class="col-xs-4 col-sm-4 col-md-4 col-lg-4">
<div class="form-group">
<label for="">Last Name</label>
<input type="text"name="last_name" class="form-control" id="" placeholder="">
</div>
</div>
</div>
<div class="form-group">
<label for="">Email Address</label>
<input type="text" name="email_address" id="input" class="form-control" value="" required="required" pattern="" title="">
</div>
<div class="form-group">
<label for="">Profile Summary</label>
<textarea name="" id="input" name="profile_summary" class="form-control" rows="3" required="required"></textarea>
</div>
<p class="bold m-b-10">Open for following type</p>
<div class="check-box-group">
<label class="checkbox-inline">
<input type="checkbox" id="inlineCheckbox1" value="option1"> Freelance Project
</label>
<label class="checkbox-inline">
<input type="checkbox" id="inlineCheckbox2" value="option2"> Contract Project
</label>
<label class="checkbox-inline">
<input type="checkbox" id="inlineCheckbox3" value="option3"> Part Time Hire
</label>
<label class="checkbox-inline">
<input type="checkbox" id="inlineCheckbox3" value="option3"> Direct Hire ( Full time )
</label>
<label class="checkbox-inline">
<input type="checkbox" id="inlineCheckbox3" value="option3"> SOW
</label>
</div>
<div class="m-t-20 m-b-20">
Continue
</div>
</form>
My controller:
public function addTalent(Request $request)
{
$rules = array(
'first_name' => 'required',
'middle_name' => 'required',
'last_name' => 'required',
'email_address' => 'required',
'profile_summary' => 'required',
);
$validator = \Illuminate\Support\Facades\Validator::make(Input::all(), $rules);
if ($validator->fails()) {
return Redirect::to('add-talent-1')
->withErrors($validator);
} else {
// store
$talent = new Talent();
$talent->first_name = Input::get('first_name');
$talent->middle_name = Input::get('middle_name');
$talent->last_name = Input::get('last_name');
$talent->email_address = Input::get('email_address');
$talent->profile_summary = Input::get('profile_summary');
$talent->save();
}
}
and my model:
class Talent extends Model
{
protected $table = 'add_talent_1';
protected $fillable = ['first_name','middle_name','last_name','email_address','profile_summary'];
}
and my routes/web.php
Route::post('add/talent', 'AddTalent#addTalent');
if i test my route under routes/api.php usig postman and hit my post request it successfully add data into database using url: http://127.0.0.1:8000/api/add/talent
but if i removed api and simply hit request using url http://127.0.0.1:8000/add/talent it says TokenMismatchException in VerifyCsrfToken.php line 68
i dont know where i am doing my wrong why my form is not submitting my data
Any help will be highly appreciated!
By default Laravel uses the csrf middleware in web routes to check and verify whether the request has a valid csrf token. This is not applicable in api routes, so it will work in your case when you send the request with postman. But you cannot do the same for a route defined in web.php.
Laravel offers a solution for this in their documentation though. You can add an exception for this route in csrf middleware.
However, you may also exclude the routes by adding their URIs to the
$except property of the VerifyCsrfToken middleware:
https://laravel.com/docs/5.4/csrf#csrf-excluding-uris
You can find this middleware in:
app/Http/Middleware/VerifyCsrfToken.php
<?php
namespace App\Http\Middleware;
use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as BaseVerifier;
class VerifyCsrfToken extends BaseVerifier
{
/**
* The URIs that should be excluded from CSRF verification.
*
* #var array
*/
protected $except = [
'add/talent',
];
}
Once you add the exception, you should be able to send the request using postman! Generally, it's recommended to put such routes in api.php, not in web.php. Csrf validation is a security feature given by Laravel and you shouldn't be excluding it unless you have a good reason to do so :)
Hope it helps. Feel free to ask if you have any doubts.

Posting to the same form in laravel

I'm trying to build a search form in Laravel such that when a user presses the search button, all the contacts matching the search criteria are displayed on the same page.
Below is my form:
{{ Form::open(array('url' => '/directory', 'class' => 'form-horizontal')) }}
<div class="form-group">
<label for="lastname" class="col-sm-2 control-label">Last Name</label>
<div class="col-sm-6">
<input type="text" class="form-control" id="lastname" placeholder="Enter Last Name">
</div>
</div>
<div class="form-group ">
<label for="phone" class="col-sm-2 control-label">Phone</label>
<div class="col-sm-6">
<input type="text" class="form-control" id="phone" placeholder="Enter Phone number">
</div>
</div>
<div class="form-group">
<label for="inputEmail1" class="col-sm-2 control-label">Email</label>
<div class="col-sm-6">
<input type="email" class="form-control" id="inputEmail1" placeholder="Enter Email - leave blank if you are not sure">
</div>
</div>
<div class="form-group">
<div class="col-lg-offset-2 col-lg-10">
<button type="submit" class="btn-u btn-u-green">Search</button>
</div>
</div>
<div class="well">
#foreach($users as $user)
<li>{{$user->firstname}} {{$user->lastname}}</li>
#endforeach
</div>
{{ Form::close() }}
The screenshot below gives a pictorial view of my form:
My route is defined as follow:
Route::get('/directory', 'UsersController#filter');
Now, whenever I press the search button, I am getting a MethodNotFound exception.
What I really want to do is to show the search results below the search button.
Edit ..
Everything is working fine now except for one thing.
I'm displaying the data in my view (getting the list of all the users on my page which match the search criteria) but the for loop is not getting executed.
<li>Count of users = {{ $users->count() }}</li>
<li>{{$users->first()->lastname}}</li>
#foreach ($users as $user)
<p>This is user {{ $user->id }}</p>
#endforeach
So: while I can see the count and the lastname of the first user in the resultant array of records, the foreach loop is not getting executed.
What am I doing wrong?
Laravel routes are bound to the form METHOD, so you need to create also a POST route:
Route::post('/directory', 'UsersController#filter');
You also need to add names to your form fields:
name="lastname"
for
<input type="text" name="lastname" class="form-control" id="lastname" placeholder="Enter Last Name">
And for all the others.
A controller method to handle that query could look like this:
<?php
class UsersController extends Controller {
public function filter()
{
$users = User::query();
if (Input::has('lastname'))
{
$users->where('lastname', Input::get('lastname'))
}
if (Input::has('phone'))
{
$users->where('phone', Input::get('phone'))
}
return View::make('your.view')
->with('userCount', $users->count());
->with('users', $users->get());
}
}
And in your view you can just:
<li>Count of users = {{$userCount}}</li>
#foreach ($users as $user)
<li>
{{ $user->id }} - {{$user->lastname}}
</li>
#endforeach
You have to tell Laravel that you want to use get method for submitting a form to the server. otherwise, Laravel will use post method by default.
Try the following:
{{ Form::open(array('url' => '/directory', 'method' => 'get', 'class' => 'form-horizontal')) }}
^^^

Categories