updating of records in laravel 4.2 - php

Hello im new in laravel 4.2 and i m making an application in the controllers, i made my own function called c_updateSystemUser($id) and here is the code
public function c_updateSystemUser($id)
{
//
session_start();
$getsCapt = $_SESSION["captcha"];
$rules = array(
'username' => 'required|min:2|max:50|regex:/^[a-zA-Z0-9\-\s]+$/|exists:dbo_systemusers,SystemUserName,$id',
'description' => 'required|min:1|max:100|regex:/^[a-zA-Z0-9\-\s]+$/',
'usertype' => 'required|numeric',
'capt' => 'required|numeric'
);
$validator = Validator::make(Input::all(), $rules);
// process the inputs given by the user
if ($validator->fails())
{
return Redirect::to('viewsu/' . $id)
->withErrors($validator)
->withInput(Input::except('password'));
}
else
{
// store the values into the database
$su = SystUser::find($id);
$su->SystemUserTypeID = Input::get('usertype');
$su->SystemUserName = Input::get('username');
$su->SystemUserDescription = Input::get('description');
$su->timestamps = false;
$su->save();
Session::flash('message', 'Successfully created system user!');
return Redirect::to('viewsu');
}
}
}
i wanted this function to be called when the user clicked the update button on my view file but when the button is clicked, it is redirecting to some other page (my create user page) i don't know why
here is the code of my form in my blade
{{ Form::model($su, array('route' =>array('csu.update',$su->SystemUserID),'method'=>'PUT'))}}
<div class="form-group">
{{ Form::label('usertype', 'User Type') }}
{{ Form::select('usertype', [null=>'Please Select user type'] + $sTyp , array('class'=>'form-control'))}}
{{ Form::label('current' , 'Current Type: (unedited) '.$su->SystemType , array('class' => 'label label-primary')) }}
</div>
<div class="form-group">
{{ Form::label('username', 'Username') }}
{{ Form::text('username', $su->SystemUserName, array('class' => 'form-control')) }}
</div>
<div class="form-group">
{{ Form::label('description', 'Description') }}
{{ Form::textarea('description', $su->SystemUserDescription, array('class' => 'form-control','rows' => '3')) }}
</div>
<div class="form-group">
{{ Form::label('captcha', 'CAPTCHA image: ') }}
</br>
{{ HTML::image('http://localhost:8080/laravel3/app/captcha.php', 'alt' , array( 'width' => 200, 'height' => 35 )) }} </br></br>
{{ Form::text('capt', Input::old('capt'), array('class' => 'form-control','placeholder' => 'enter generated captcha')) }}
</div>
{{ Form::submit('Edit System User', array('class' => 'btn btn-primary')) }}
{{ Form::close()}}
i don't know how to make the form call the function public function c_updateSystemUser($id) in my controller
my controller file is called systemUsers.php
any ideas? any help would be appreciated

If your view name is update and its in views->csu folder you can do it like following
{{ Form::model($su, array('route' =>array('csu.update.c_updateSystemUser',$su->SystemUserID),'method'=>'PUT'))}}
#yourentry
{{Form::close()}}
Your route should be like following:
Route::resource('csu','systemUsers');
In systemUsers.php add c_updateSystemUser($id){} method.

Related

Neither it show an error nor save the Data into my database PHP Laravel?

I am trying to insert data into the database neither it shows an error nor saves the data into my database below are the codes. here is the create blade php page .
#extends('layouts.app')
#section('content')
<h1>Create a Camp</h1>
<!-- if there are creation errors, they will show here -->
{{ HTML::ul($errors->all()) }}
{{ Form::open(array('url' => 'camps')) }}
<div class="form-group">
{{ Form::label('name', 'Name') }}
{{ Form::text('name', Request::old('name'), array('class' => 'form-control')) }}
</div>
<div class="form-group">
{{ Form::label('district', 'District') }}
{{ Form::text('district', Request::old('district'), array('class' => 'form-control')) }}
</div>
<div class="form-group">
{{ Form::label('address', 'Address') }}
{{ Form::text('address', Request::old('address'), array('class' => 'form-control')) }}
</div>
<div class="form-group">
{{ Form::label('block', 'Block') }}
{{ Form::text('block', Request::old('block'), array('class' => 'form-control')) }}
</div>
<div class="form-group">
{{ Form::label('population', 'population') }}
{{ Form::text('population', Request::old('population'), array('class' => 'form-control')) }}
</div>
{{ Form::submit('Create the Camp!', array('class' => 'btn btn-primary')) }}
{{ Form::close() }}
#endsection
here is the controller the index controller works fine when I manually enter the data it fetches from the database
here is the store controller and also it not validate the forms data , i am new i dont know how to do it
public function store(Request $request)
{
$rules = array(
'name' => 'required',
'district'=> 'required',
'address' => 'required',
'block' => 'required|numeric',
'Population' => 'required|numeric',
);
$validator = Validator::make(Request::all(), $rules);
if ($validator->fails()) {
return Redirect::to('camp/create')
->withErrors($validator)
->withRequest(Request::except('password'));
} else {
// store
$camp = new Camp;
$camp->name = Request::get('name');
$camp->district = Request::get('district');
$camp->address = Request::get('address');
$camp->block = Request::get('block');
$camp->population = Request::get('population');
$camp->save();
// redirect
Session::flash('message', 'Successfully created Camp!');
return view('camp\camps',['camps'=>$camps]);
}
}
You forgot to add parenthesis after Camp it should be like this:
$camp = new Camp();
$camp->name = $request->name;
$camp->district = $request->district;
$camp->save();

Field 'user_id' is empty

Today I have made a comments system, but isn't completed.In my database I have all fields filled by dates, but user_id isn't.How can I be able to save in column user_id, the id of authenticated user?Here is my code.
CommentsController:
public function store(Request $request, $post_id)
{
$this->validate($request, array(
'username' => 'required|max:255',
'mail' => 'required|mail|max:255',
'comment' => 'required|min:5|max:2000',
));
$post = Post::find($post_id);
$comment = new Comment();
$comment->username = $request->username;
$comment->email = $request->email;
$comment->comment = $request->comment;
$comment->approved = true;
$comment->post()->associate($post);
$comment->save();
Session::flash('message', "Message posted successfully!");
return Redirect::back();
}
My view
<div class="row">
<div id="comment-form">
{{ Form::open(['route' => ['comments.store', $post->id], 'method' => 'POST']) }}
<div class="row">
<div class="col-md-6">
{{ Form::label('username', "Username:") }}
{{ Form::text('username', null, ['class' => 'form-control']) }}
</div>
<div class="col-md-6">
{{ Form::label('email', "Email:") }}
{{ Form::text('email', null, ['class' => 'form-control']) }}
</div>
<div class="col-md-6">
{{ Form::label('comment', "Comment:") }}
{{ Form::text('comment', null, ['class' => 'form-control']) }}
</div>
{{ Form::submit('Add Comment', ['class' => 'btn btn-success btn-xs']) }}
</div>
{{ Form::close() }}
</div>
My route
Route::post('comments/{post_id}', ['uses' => 'CommentsController#store', 'as' => 'comments.store']);
I tried to put Auth::user()->id inside my form, but I failed...
For you get the authenticated user you should only use the Auth facade. I show how to use it below.
use Illuminate\Support\Facades\Auth;
$user = Auth::user(); // Get the currently authenticated user...
$user_id = Auth::id(); // Get the currently authenticated user's ID...
Therefore, to save a user associated in a comment you have two options:
$user_id = Auth::id();
$comment->user_id = $user;
$comment->save();
Or
$user = Auth::user();
$comment->user = $user;
$comment->save();
If you have more questions about Laravel authentication take a look at https://laravel.com/docs/5.8/authentication#retrieving-the-authenticated-user.

localhost is currently unable to handle this request. HTTP ERROR 500 with Laravel

I am trying to edit a JSON formatted category with PUT method, so I am using guzzleHttp library to parse json requests and responses with laravel 5.5.
My POST, GET methods are working fine when I am trying to grab or insert data into my server, but I am getting error on PUT & DELETE method.
There are two types of errors I am getting :
localhost is currently unable to handle this request. HTTP ERROR 500
Out Of Memory - Fatal error: Out of memory (allocated 1472200704) (tried to allocate 176128 bytes)
Console Error :
These errors occurs not together just one after another if I request twice in row.
I have trying to change allocated memory, but it did not work !
Here are my procedures to handle a request :
My Controller :
public function update(Request $request, $id)
{
// get the inputs
$inputs = [
"cat_id" => $id,
"cat_name" => $request->input('cat_name'),
"cat_slug" => $request->input('cat_slug'),
"cat_description" => $request->input('cat_description'),
"cat_parent_id" => $request->input('cat_parent_id')
];
// post to the database
$response = $this->categories->update($id, $inputs);
if($response['success']){
$message = $response['message'];
Session::flash('success', 'Category is successfully saved !'.' Server Response Message : '.$message);
return redirect()->route('categories.index');
}else{
$message = $response['message'];
Session::flash('success', 'Category is not successfully saved !'.' Server Response Message : '.$message);
return redirect()->route('categories.index');
}
/////////////////////////////////////////////////
// If the edit page should be shown
//return redirect()->route('categories.edit', $id);
}
My Repository :
public function update($id, $category){
return $this->update("categories/{$id}", $category);
}
And My Custom GuzzleHttpRequest.php :
protected function update($url, $data){
$formatted_data = json_encode($data);
$request = $this->client->request('PUT', $url, [
'body' => $formatted_data
]);
$response = json_decode( $request->getBody()->getContents() , true );
return $response;
}
My Server Accepts JSON formatted inputs : https://rest-banai.herokuapp.com/
Edited :
And My Edit Form :
{!! Form::open(['route' => ['categories.update', $category['cat_id']], 'method' => 'PUT', 'data-parsley-validate' => '']) !!}
<div class="form-group">
{{ Form::label('cat_name', 'Name:') }}
{{ Form::text('cat_name', $category['cat_name'], ['class' => 'form-control', 'placeholder' => 'Enter category name ...', 'required' => '', 'maxlength' => '50']) }}
</div>
<div class="form-group">
{{ Form::label('cat_slug', 'Slug:') }}
{{ Form::text('cat_slug', $category['cat_slug'], ['class' => 'form-control', 'placeholder' => 'Enter a slug word ...', 'required' => '', 'maxlength' => '50', 'data-parsley-type' => 'alphanum']) }}
</div>
<div class="form-group">
{{ Form::label('cat_description', 'Description:') }}
{{ Form::textarea('cat_description', $category['cat_description'], ['class' => 'form-control', 'rows' => '3', 'placeholder' => 'Enter description of the category ...', 'maxlength' => '255']) }}
</div>
<div class="form-group">
{{ Form::label('cat_parent_id', 'Parent Category:') }}
<br />
{{ Form::select('cat_parent_id', $cat_array, null, ['placeholder' => $cat_parent_name]) }}
<br />
</div>
<div class="pull-right">
{{ Form::submit('SAVE', ['class' => 'btn btn-block btn-success btn-sm']) }}
</div>
{!! Form::close() !!}
I am not sure what is I am doing wrong here, any expert, please help me with the issue as I am new with Guzzle and JSON working with Laravel, it will be appreciated.
And If anythings unclear here, please suggest to edit.
Thanks In Advance !
Change your request to
$request = $this->client->request('PUT', $url,['json'=> $data]);
You are using resourceful routes, and yet you have a lot of complexity in your code. This quite frankly in my opinion is completely unnecessary. I will accomplish what you are doing in the following way:
Routes
Route::resource('category', 'CategoryController');
Controller
public function edit(Category $category)
{
return view('category.edit', compact('category'));
}
public function update(Request $request, Category $category)
{
try {
$category->update($request->all()->except(['_token']));
Session::flash('success', 'Category is successfully saved !');
} catch(\Exception $exception) {
Session::flash('error', 'Unable to update category!');
}
return redirect(route('category.index'));
}
HTML
category/edit.blade.php
{!! Form::open(['route' => route('categories.update', $category), 'method' => 'PUT', 'data-parsley-validate' => '']) !!}
<div class="form-group">
{{ Form::label('cat_name', 'Name:') }}
{{ Form::text('cat_name', $category->cat_name, ['class' => 'form-control', 'placeholder' => 'Enter category name ...', 'required' => '', 'maxlength' => '50']) }}
</div>
<div class="form-group">
{{ Form::label('cat_slug', 'Slug:') }}
{{ Form::text('cat_slug', $category->cat_slug, ['class' => 'form-control', 'placeholder' => 'Enter a slug word ...', 'required' => '', 'maxlength' => '50', 'data-parsley-type' => 'alphanum']) }}
</div>
<div class="form-group">
{{ Form::label('cat_description', 'Description:') }}
{{ Form::textarea('cat_description', $category->cat_description, ['class' => 'form-control', 'rows' => '3', 'placeholder' => 'Enter description of the category ...', 'maxlength' => '255']) }}
</div>
<div class="form-group">
{{ Form::label('cat_parent_id', 'Parent Category:') }}
<br />
{{ Form::select('cat_parent_id', $cat_array, null, ['placeholder' => $cat_parent_name]) }}
<br />
</div>
<div class="pull-right">
{{ Form::submit('SAVE', ['class' => 'btn btn-block btn-success btn-sm']) }}
</div>
{!! Form::close() !!}
```

Pagination after search only works on the first page

The first page will be sorted correctly. However, the second page (and further) will go back to being as if no fields in the search were filled at all.
I am collecting the search fields in the form below:
{{ Form::open(['route' => 'admin.users.search', 'method' => 'get', 'class' => 'navbar-form navbar-left form-inline', 'role' => 'search']) }}
<div class="form-group">
{{ Form::text('user_id', request('user_id'), ['class' => 'form-control', 'size' => '8', 'placeholder' => 'ID']) }}
</div>
<div class="form-group">
{{ Form::email('email', request('email'), ['class' => 'form-control', 'size' => '20', 'placeholder' => 'Email']) }}
</div>
<div class="form-group">
{{ Form::text('first_name', request('first_name'), ['class' => 'form-control', 'size' => '20', 'placeholder' => 'First Name']) }}
</div>
<div class="form-group">
{{ Form::text('family_name', request('family_name'), ['class' => 'form-control', 'size' => '20', 'placeholder' => 'Family Name']) }}
</div>
<div class="form-group">
<div class="selectize-lg">
{{ Form::select('institution_id', $institutions, request('institution_id'), ['class' => 'form-control', 'size' => '200', 'data-selectize']) }}
</div>
</div>
<div class="form-group">
<div class="selectize-lg">
{{ Form::select('exam_id', $exams, request('exam_id'), ['class' => 'form-control', 'data-selectize']) }}
</div>
</div>
<div class="form-group ">
{{ Form::submit('Search', ['class' => 'btn btn-default']) }}
</div>
Clear
{{ Form::close() }}
Once the form has been submitted it will hit a GET route
Route::get('members/search', 'UsersController#search')->name('admin.users.search');
Then the users controller:
$users = User::with('exam', 'institution');
if ($request->has('user_id')) {
$users->whereId($request->user_id);
}
if ($request->has('email')) {
$users->whereEmail($request->email);
}
if ($request->has('first_name')) {
$users->where('first_name', 'LIKE', "%{$request->first_name}%");
}
if ($request->has('family_name')) {
$users->where('family_name', 'LIKE', "%{$request->family_name}%");
}
if ($request->has('institution_id')) {
$users->whereInstitutionId($request->institution_id);
}
if ($request->has('exam_id')) {
$users->whereExamId($request->exam_id);
}
$users = $users->latest()->paginate(48);
$usersTotal = $users->total();
$exams = ['' => 'Exam...'] + Exam::orderBy('title')
->pluck('title', 'id')
->all();
$institutions = ['' => 'University...'] + Institution::orderBy('name')
->pluck('name', 'id')
->all();
return view('admin.users.index', compact('users', 'usersTotal', 'exams', 'institutions'));
Then, in the view I am adding the pagination links like this:
{{ $users->appends(array_filter(request()->except('page')))->render() }}
However, the search results only work on the first page. for example, the route on the first page will look like this:
search?user_id=&email=hello%40world&first_name=John&family_name=Smith&institution_id=1&exam_id=1
But the second page will look like this:
search?page=2
I am finding this pretty puzzling and not too sure what is causing the search to fail on the second page.
From the docs:
Appending To Pagination Links
You may append to the query string of pagination links using the
appends method. For example, to append sort=votes to each pagination
link, you should make the following call to appends:
{{ $users->appends(['sort' => 'votes'])->links() }} If you wish to
append a "hash fragment" to the paginator's URLs, you may use the
fragment method. For example, to append #foo to the end of each
pagination link, make the following call to the fragment method:
{{ $users->fragment('foo')->links() }}
You are almost on the right track with this:
{{ $users->appends(array_filter(request()->except('page')))->render() }}
Wat this peace of code does is carry over the page-request when you switch pages, which is necessary since that is done for you. So you will need to specify the request data that you would like to keep. So for example:
{{ $users->appends(Request::except('page'))->links() }}
will add all request data to the next page, except the pagination links because that is added by default.
Note: i notice that you are sending id's with GET requests , please be carefull doing that. Users with bad intentions can see you database structure and possible take use of it.

Simple contact form not showing validation errors or sending the message

I have a simple contact form in Laravel 5. If I submit it with empty fields, the page reloads but it doesn't show me the error messages of the validation. If I fill in the form and submit, I get this error:
InvalidArgumentException in FileViewFinder.php line 140: View [emails.message] not found.
That's because I don't have such view, I'm not sure what to put in it and Laravel's documentation is not clear on the subject:
The first argument passed to the send method is the name of the view that should be used as the e-mail body.
Not sure what that means.
Routes
Route::get('contact','HomeController#contactus');
Route::post('contact_request', 'HomeController#contactRequest');
HomeController
public function contactus()
{
if (Auth::check()) {
$count = Cart::count();
} else {
$count = 0;
}
$contact = Contact::all();
return view('contact')->with('contact', $contact)->with('count', $count);
}
public function contactRequest() {
if (Auth::check()) {
$count = Cart::count();
} else {
$count = 0;
}
$contact = Contact::all();
//Get all the data and store it inside Store Variable
$data = Input::all();
//Validation rules
$rules = array (
'name' => 'required',
'email' => 'required|email',
'message' => 'required|min:5'
);
//Validate data
$validator = Validator::make ($data, $rules);
//If everything is correct than run passes.
if ($validator -> passes()){
Mail::send('emails.message', $data, function($message) use ($data)
{
//$message->from($data['email'] , $data['first_name']); uncomment if using first name and email fields
$message->from('feedback#gmail.com', 'feedback contact form');
//email 'To' field: cahnge this to emails that you want to be notified.
$message->to('feedback#gmail.com', 'John')->cc('feedback#gmail.com')->subject('feedback form submit');
});
// Redirect to page
return view('contact')
->with('message', 'Your message has been sent. Thank You!');
//return View::make('contact');
}else{
//return contact form with errors
return view('contact')
->with('error', 'Feedback must contain more than 5 characters. Try Again.')
->with('contact', $contact)
->with('count', $count);
}
}
View
<h1 class='siteh1'>Contact Us</h1>
<hr class='sitehr'/>
<div class="col-md-6 siteleft">
<h2 class='siteh2'>Contact Info</h2>
<div class='contaddr'><label>Address:</label> {!!$contact[0]['Address']!!}</div>
<div class='contphone'><label>Phone:</label> {!!$contact[0]['Phone1']!!} | {!!$contact[0]['Phone2']!!}</div>
<div class='contemail'><label>E-mail:</label> {!!$contact[0]['Email']!!}</div>
<div class='contfollow'><label>Follow us:</label><p>
<img src="images/fb.png" alt="Facebook">
<img src="images/youtube.png" alt="Youtube">
<img src="images/skype.png" alt="Skype">
<img src="images/gplus.png" alt="Google Plus">
</p></div>
</div>
<div class="col-md-4 col-md-offset-2 col-sm-12 col-xs-12">
<p class='siteright'>
Get in touch with us
</p>
<div class='contform'>
{!! Form::open(['action' => 'HomeController#contactRequest', 'METHOD' => 'PUT']) !!}
<ul class="errors">
#foreach($errors->all('<li>:message</li>') as $message)
#endforeach
</ul>
<div class="form-group">
{!! Form:: text('name', '', array('placeholder' => 'Your Name', 'class' => 'form-control', 'id' => 'contname', 'rows' => '4' )) !!}
</div>
<div class="form-group">
{!! Form:: text('email', '', array('placeholder' => 'Your Email', 'class' => 'form-control', 'id' => 'contemail', 'rows' => '4' )) !!}
</div>
<div class="form-group">
{!! Form:: text('phone', '', array('placeholder' => 'Your Phone', 'class' => 'form-control', 'id' => 'contphone', 'rows' => '4' )) !!}
</div>
<div class="form-group">
{!! Form:: textarea('message', '', array('placeholder' => 'Message', 'class' => 'form-control', 'id' => 'contmessage', 'rows' => '4' )) !!}
</div>
</div>
<div class="modal-footer">
{!! Form::submit('Submit', array('class' => 'btn btn-primary')) !!}
{!! Form:: close() !!}
</div>
</div>
Emails are just blade templates, and the dots note the directory structure. Blade templates are stored in resources/views, so in this case, emails.message will cause Laravel to look in resources/views/emails for the file message.blade.php.
Create the file resources/views/emails/message.blade.php with the content of your message.
All of the data from the form is being passed (via the $data argument), so you should be able to access it in the message view file like this.
Hello {{ $name }}, your phone number is {{ $phone }}
As far as the main view template goes, your error handling code should be:
#foreach($errors->all() as $message)
<li>{{ $message }}</li>
#endforeach`

Categories