I am trying to insert data in my database.But I can't to do it. I try my best. I know its a simple question.
Here is my route:
Route::post('/class', [
'uses' => 'classroom#showdata',
'as' => 'classrooms']);
Here is my Controller:
public function showclass(Request $request)
{
$randomnumber = rand(50001,1000000);
$classrooms = new Classrooms();
$classrooms->class_name = $request['class_name'];
$classrooms->subject_name = $request['subject_name'];
$classrooms->section = $request['section'];
$classrooms->class_code = $randomnumber;
$classrooms -> user_id = Auth::user()->id;
$classrooms -> save();
return view('class', array('classroom' => Auth::user()) );
}
Here is my form:
<form class="form-horizontal" role="form" method="POST" action="{{ url('/class') }}">
{!! csrf_field() !!}
Where is my mistake?
There is an error in your Route. You have used showdata method instead of showclass. Just change it like below:
Route::post('/class', [
'uses' => 'classroom#showclass',
'as' => 'classrooms']);
Note: Make sure to specify specific method while defining the routes.
Related
This is my route: it works fine, I can see dumps if I do it inside the get Method and middleware is working fine as well
Route::get('account', 'AccountController#get')->middleware('auth');
This is my controller: I dump accountData and has value, also dump user and is the right user, so accountData is correct, but at first time loading the page comes variable undefined but if I refresh it loads fine
class AccountController extends Controller
{
public function get()
{
$user = auth()->user();
$account = $this->getAccountQuery($user->id);
$accountData = $this->formatAccount($account, $user->id);
return view('account')->with($accountData);
}
This is the format method:
private function formatAccount($account, $userId): array
{
return [
'accountId' => $account->id,
'name' => (ucwords($account->first_name) . ' ' . ucwords($account->last_name)) ?? 'NA',
'email' => $account->email ?? 'NA',
'idType' => $account->id_type ?? 'NA',
'idNumber' => $account->id_number ?? 'NA',
'primaryTelephone' => $account->primary_telephone ?? 'NA',
'secondaryTelephone' => !empty($account->secondary_telephone) ? $account->secondary_telephone : 'NA',
'primaryAddress' => $account->primary_address ?? 'NA',
'secondaryAddress' => !empty($account->secondary_address) ? $account->secondary_address : 'NA',
'city' => ucwords($account->city) ?? 'NA',
'country' => ucwords($account->country) ?? 'NA',
'delivery' => $account->delivery,
'pickup' => $account->pick_up,
'authUsers' => $this->getAuthUsers($userId)
];
}
This is how I call it in my blade:
If I refresh the page it works fine, only is happening the first time I load it
<p>
<label id='label1'>Name
<input type="text" name="name" placeholder={{ $name }} required>
</label>
</p>
I'm using Laravel 5.7 I'm trying to route my function for get and post.
I want to load a view and post a form.
As I have studied
Route::match(['GET','POST'], '/', TestController#test);
Route::any('/', TestController#test);`
one of these should work.
But its not working for me,is there any other way or I'm doing something wrong?
UPDATE
Route to admin:
Route::match(['get','post'], 'cp/', 'AdminController#test');
Function in Admin controller:
public function test( Request $request){
$data=array();
if ($request->isMethod('POST')) {
echo "here it is";
exit;
}else{
echo "still in get!";
}
return view('admin/login', $data);
}
And my view in short is something like this:
<form action="{{ url('/cp') }}" method="POST">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<form>
Can you try changing
Route::match(['GET','POST'], '/', TestController#test);
to
Route::match(['GET','POST'], '/', 'TestController#test');
OR
Route::any('/', TestController#test);
to
Route::any('/', 'TestController#test');
The second param should be wrapped in quotes!
UPDATE:
Your route match code should be something like this :
Route::match(array('GET', 'POST', 'PUT'), "/", array(
'uses' => 'Controller#index',
'as' => 'index'
));
Try this in you web.php
Route::match(['get', 'post'], '/testMethods', function ()
{
dd('its workong bro');
});
And hit the yourprojectname/testMethods in your web browser
Eg: http://localhost:8000/testMethods
From Illuminate\Contracts\Routing\Registrar.php
public function match($methods, $uri, $action);
Here is match function parameter list
Parameter One List of methods: Eg: get,post,put,patch
Parameter two url : Eg: /testMethods
Parameter three Method: Eg: TestController#test
Route::match(['get', 'post'], '/testMethods','TestController#test');
Well, by the end what I understand to use route::match I should specify function name without it it will not work.So when I changed it to Route::match(array('GET', 'POST', 'PUT'), "/login", array(
'uses' => 'AdminController#login',
'as' => 'login'
));
It resolves the issue. Thank for the help everyone!!
The concerning route:
Route::patch('admin/track/practice/{practice_id}/close-practice-session/{session_id}/{new?}', array(
'as' => 'close-practice-session',
'uses' => 'AdminController#closePracticeSession'
));
new is an optional route parameter.
The Controller method:
public function closePracticeSession($club, $practice_id, $session_id, $new = null)
{
$clubDetails = new ClubDetails();
$club_id = $clubDetails->getClubID($club);
date_default_timezone_set(config('app.timezone'));
$CurrentTime = date("Y-m-d H:i:s");
try
{
DB::table('practice_sessions')
->where('id', $session_id)
->where('club_id', $club_id)
->update(['is_current' => 0, 'updated_at' => $CurrentTime]);
if ($new == 'Y')
{
return redirect()->action('AdminController#getTrackPracticeSession', [$club, $practice_id]);
}
else
{
return redirect()->action('AdminController#getTrackPracticeSession', [$club, $practice_id, $session_id])
->with(array('success'=>'Practice was successfully closed.'));
}
}
catch(\Exception $e)
{
return view('errors.500')->with(self::getRequiredData($club))->with('error', $e->getMessage());
}
}
I have two forms on my view, one has the optional parameter, one doesn't.
When I click on the button on the form which has the optional parameter, I am getting a BLANK screen.
Here are some strange things:
No error message. Checked the laravel.log
Even if I remove all the logic from the controller method and do a
simple var_dump, I still get a blank screen
When I click on the button without the optional parameter, it
behaves as expected
I have been trying for the last two days to resolve this without any luck. I have even tried to make the {new} parameter mandatory. Anytime I am passing the last parameter, I am getting a blank screen.
Any idea? I am sure I am doing something silly. Just can't see it.
Update (the two forms on the view) - the csrf token is in the header.
{!! Form::open([
'method' => 'PATCH',
'route' => ['close-practice-session', $alias, $practiceDetails[0]->practice_id, $practiceDetails[0]->id]
]) !!}
{!! Form::submit('Close Session', ['class' => 'btn btn-primary btn-sm', 'style' => 'width: 160px;margin-left: 0px!important']) !!}
{!! Form::close() !!}
<!-- #2 -->
{!! Form::open([
'method' => 'PATCH',
'route' => ['close-practice-session', $alias, $practiceDetails[0]->practice_id, $practiceDetails[0]->id, "Y"]
]) !!}
{!! Form::submit('Close + Create New', ['class' => 'btn btn-secondary btn-sm', 'style' => 'width: 160px;margin-left: 0px!important']) !!}
{!! Form::close() !!}
As per your route
Route::patch('admin/track/practice/{practice_id}/close-practice-session/{session_id}/{new?}', array(
'as' => 'close-practice-session',
'uses' => 'AdminController#closePracticeSession'
));
Your controller function should be like this
public function closePracticeSession(Request $request, $practice_id, $session_id, $new = null)
{
$clubDetails = new ClubDetails();
$club_id = $clubDetails->getClubID($club);
date_default_timezone_set(config('app.timezone'));
$CurrentTime = date("Y-m-d H:i:s");
try
{
DB::table('practice_sessions')
->where('id', $session_id)
->where('club_id', $club_id)
->update(['is_current' => 0, 'updated_at' => $CurrentTime]);
if ($new == 'Y')
{
return redirect()->action('AdminController#getTrackPracticeSession', [$club, $practice_id]);
}
else
{
return redirect()->action('AdminController#getTrackPracticeSession', [$club, $practice_id, $session_id])
->with(array('success'=>'Practice was successfully closed.'));
}
}
catch(\Exception $e)
{
return view('errors.500')->with(self::getRequiredData($club))->with('error', $e->getMessage());
}
}
Please take a look at this SO post. This gave me a hint to solve my problem. I had an identical GET route in my routes.php file. Once I modified my PATCH route to the following, everything is working as expected.
Route::patch('admin/close-practice-session/{practice_id}/{session_id}/{new?}', array(
'as' => 'close-practice-session',
'uses' => 'AdminController#closePracticeSession'
));
I think I might have discovered a bug. This is what I have until now.
Routes.php
Route::get('/{user}/{char_dynasty}/{char_name}/selectedok', array(
'as' => 'char-profile-get',
'uses' => 'CharacterController#getDropDownList'));
Route::post('/user/{user}/{char_dynasty}/{char_name}/selectedok', array(
'as' => 'char-profile-post',
'uses' => 'CharacterController#postDropDownList'));
CharacterController.php
class CharacterController extends BaseController{
public function getDropDownList($user, $char_dynasty, $char_name)
{
if(Auth::check())
{
$user = Auth::user();
return View::make('layout.notification', array(
'user' => $user,
'char_dynasty' => $char_dynasty,
'char_name' => $char_name));
}
else
{
return App::abort(404);
}
}
public function postDropDownList()
{
if (Auth::check())
{
$user = Auth::user();
$char_name = User::find($user->id)->characters()->where('char_name', '=', Input::get('choose'))->first();
return Redirect::route('char-profile-get', array(Session::get('theuser'),
$char_name->char_dynasty,
$char_name->char_name));
}
}
}
profile.blade.php (snippet)
<form action="{{ URL::route('char-profile-post') }}" method="post">
<select name="choose">
<option value="choose">Choose a character</option>
<option> {{ $c_name }} </option>
</select>
<input type="submit" value="Ok">
{{ Form::token() }}
</form>
The error says that $char_dynasty is undefined which is usually used
<option> {{ $char_dynasty }} </option>
I changed to populate the drop down list with another variable to be able to execute the database query $char_name from postDropDownList.
If I do in function getDropDownList, var_dump($char_dynasty); var_dump($char_name) I get the following
string 'Spirescu' (length=8)
string 'Ion' (length=3)
The point is that the parameters in getDropDownList are with the correct data, but are not transfered to the View. What am I doing wrong? I don't know how to access the variables in the View?
I have also tried return View::make('layout.notification', compact('user' , 'char_dynasty' , 'char_name' ));
or
$data = array(
'user' => $user,
'char_dynasty' => $char_dynasty,
'char_name' => $char_name);
return View::make('layout.notification', $data);
I receive the same error. or $data is not defined.
I'm using the Laravel 4 password reminder functionality, as described here: http://four.laravel.com/docs/security#password-reminders-and-reset. In order to generate the token, send the email and create de DB record in the password_reminder table, I use the standard code in my routes file :
Route::post('password/remind', function() {
$credentials = array('email' => Input::get('email'));
return Password::remind($credentials);
});
This code is suppose to send me back to my input form in case of any error (unknown email address for instance). Instead of that, I get a MethodNotAllowedHttpException. The reason is Laravel don't try to send me back to my form URL (which is /password/forgot): he tries to redirect me to /password/remind, in GET, and this route does not exist (of course) in my routes.php file.
I checked the code of the Illuminate\Auth\Reminders\PasswordBroker class, which is responsible of this redirection, and found out this method :
protected function makeErrorRedirect($reason = '')
{
if ($reason != '') $reason = 'reminders.'.$reason;
return $this->redirect->refresh()->with('error', true)->with('reason', $reason);
}
I replaced $this->redirect->refresh() by $this->redirect->back(), and everything is now working as excepted. But as I couldn't find any comment on this bug anywhere, I assume I'm doing something wrong… But I can't find what !
Here is my routes.php file:
Route::get('password/forgot', array('as' => 'forgot', 'uses' => 'SessionsController#forgot'));
Route::post('password/remind', function() {
$credentials = array('email' => Input::get('email'));
return Password::remind($credentials);
});
Route::get('password/reset/{token}', function($token) {
return View::make('sessions.reset')->with('token', $token);
});
Route::post('password/reset/{token}', array('as' => 'reset', 'uses' => 'SessionsController#reset'));
my SessionsController relevant code:
class SessionsController extends BaseController {
[...]
public function forgot() {
return View::make('sessions.forgot');
}
public function reset() {
$credentials = array(
'email' => Input::get('email'),
'password' => Input::get('password'),
'password_confirmation' => Input::get('password_confirmation')
);
Input::flash();
return Password::reset($credentials, function($user, $password) {
$user->password = Hash::make($password);
$user->save();
return Redirect::to('home');
});
}
}
and finally my view code:
{{ Form::open(array('url' => 'password/remind', 'class' => 'form', 'role' => 'form', 'method'=>'post')) }}
<div class="form-group">
{{ Form::label('email', 'E-mail') }}
{{ Form::text('email', '', array('autocomplete'=>'off', 'class' => 'form-control')) }}
</div>
{{ Form::submit("Envoyer", array("class"=>"btn btn-primary")) }}
{{ Form::close() }}
If it is possible, I highly recommend you to upgrade to Laravel 4.1, because it comes with a more flexible (also easier to understand and to work with) solution for password remind/reset.
Check out this example with Laravel 4.1:
https://github.com/laracasts/Laravel-4.1-Password-Resets/blob/master/app/controllers/RemindersController.php