I have a form that only have control on action URL. so cannot add '_token'. is that possible to get the data to my controller
External HTML form host in deference location
<!DOCTYPE html>
<html>
<head>
<title>Test HTML</title>
</head>
<body>
<form method="post" action="http://www.mylaravelproject.com/confirm">
<input type="textbox" name="fname">
<input type="textbox" name="lname">
<input type="submit">
</form>
</body>
</html>
My Laravel Route
Route::any('confirm','PageController#confirm');
Inside Controller
public function confirm(){
return Input::all();
}
Is this Possible ??
Thanks
Edit:
Found i can do that by removing line (inside App/Httm/Kenel.php)
'App\Http\Middleware\VerifyCsrfToken',
Second Question
but its kind of security risk. i Just only need to remove VerifyCsrfToken on this specific route 'confirm'.
is this possible?
This feature will be available in Laravel 5.1 out of the box.
But while we wait for Laravel 5.1 - you can do this in your App\Http\Middleware\VerifyCsrfToken file in 5.0:
<?php namespace App\Http\Middleware;
use Closure;
use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as BaseVerifier;
use Illuminate\Session\TokenMismatchException;
class VerifyCsrfToken extends BaseVerifier {
protected $excludedRouteGroups = ['confirm', 'stripe'];
public function handle($request, Closure $next)
{
if ($this->isReading($request) || ($this->excludedRoutes($request)) || $this->tokensMatch($request)) {
return $this->addCookieToResponse($request, $next($request));
}
Throw new TokenMismatchException;
}
protected function excludedRoutes($request)
{
foreach($this->excludedRouteGroups as $route) {
if ($request->segment(1) === $route) {
return true;
}
}
return false;
}
}
Related
Employees.php file
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
/**
* #method static find($id)
*/
class Employees extends Model
{
use HasFactory;
protected $table = 'employees';
public $timestamps = false;
}
EmployeesController.php
<?php
namespace App\Http\Controllers;
use App\Models\Employees;
class EmployeesController extends Controller
{
public function employees_salaries()
{
return view('director.employees_salaries');
}
public function employees()
{
$employees = Employees::all();
return view('director.employees', ['employees'=>$employees]);
}
public function destroy($id)
{
$employees = Employees::find($id);
$employees->delete();
return redirect('/director.employees')->with('status', 'Your Data is Deleted');
}
}
employees.blade.php file
<from action="/delete/{{$employee->id}}" method="POST">
#csrf
#method('DELETE')
<button type="submit" class="btn btn-delete btn-form me-3">
Delete
</button>
</from>
route.php file
Route::match(['get', 'post'], '/employees', array(EmployeesController::class, 'employees'))->name('employees');
Route::delete('/delete/{id}', array(EmployeesController::class, 'destroy'))->name('delete');
I cleared the cache but have no idea what the problem is. it looks like I wrote the function correctly
p.s version Laravel 9
mySQL 8
phpMyAdmin
Welcome to SO, i think youre not using the variable you assigned the value into,from controller in your blade view. maybe try to make sure you have the right variable or maybe try to use var dump.
try to put this in your controller b4 parsing value to view, to check whether you get the data you wanted or not
dd('$employees');
make sure you use the variable you assigned in your controller to your view
<?php
namespace App\Http\Controllers;
use App\Models\Employees;
class EmployeesController extends Controller
{
public function employees_salaries()
{
return view('director.employees_salaries');
}
public function employees()
{
$employees = Employees::all();
return view('director.employees', ['employees'=>$employees]); //<< here you name the variable 'employees'
}
public function destroy($id)
{
$employees = Employees::find($id);
$employees->delete();
return redirect('/director.employees')->with('status', 'Your Data is Deleted');
}
}
change this variable in view
<from action="/delete/{{$employee->id}}" method="POST"> //<< this one you use '$employee' instead of '$employees'
#csrf
#method('DELETE')
<button type="submit" class="btn btn-delete btn-form me-3">
Delete
</button>
</from>
there might also be other problem, but for now thats what i can point out.
since im also learning.
I am trying to login for different types of users
but I have an error starting the login view for a certain type of user
laravel default login view loads and not the one i created and assigned to protected $loginView
I cannot understand what is happening, what is the error that occurs?
Web.php:
Route::group(['middleware'=>'web'], function (){
Route::get('/', function () {
return view('welcome');
});
Route::get('admins/login','adminController#showLoginForm');
Route::get('admins/login','adminController#login');
Auth::routes();
Route::get('/home', 'HomeController#index')->name('home');
});
adminController:
<?php
namespace App\Http\Controllers;
use App\Http\Requests;
use Illuminate\Http\Request;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
class adminController extends Controller
{
use AuthenticatesUsers;
protected $loginView = 'admins.login';
}
admins >login.blade.php:
<form method ="POST" action="">
<label for="email">Email:</label>
<input type="email" name="email" id="email">
<label for="pass">password:</label>
<input type="text" name="pass" id="pass">
<button>login</button>
</form>
As far as I am aware, there is no $loginView property that Laravel utilizes to determine which view should be used for the login page, so why do you believe that it should work?
Here is the showLoginForm method:
public function showLoginForm()
{
return view('auth.login');
}
So what I would suggest you do is the following, remove the $loginView property and overwrite the showLoginForm method:
class adminController extends Controller
{
use AuthenticatesUsers;
public function showLoginForm()
{
return view('admins.login');
}
}
PS:
Why do you have the route admins/login with the method get twice?
Route::get('admins/login','adminController#showLoginForm');
Route::get('admins/login','adminController#login');
You probably meant to use post for the second one.
In my app I have a users table and a profiles table. When a user goes to their dashboard, they should be able to click a link to view their profile page. Here's the link:
link to your profile page
However, I am getting the error: Route [profiles.show] not defined.
I'm a novice and am not clear on how to link a signed up user with his/her profile page. All users should have a profile page on sign up.
I'd appreciate some guidance! Here is what I have so far:
The link to profile page
link to your profile page
ProfilesController.php
namespace App\Http\Controllers;
use App\Profile;
use Illuminate\Http\Request;
class ProfilesController extends Controller
{
public function show($id)
{
$profile = Profile::find($id);
return view('profiles.show', compact('profile'));
}
}
Profile.php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Profile extends Model
{
public function user()
{
return $this->belongsTo('User');
}
}
routes/web.php
Route::get('pages/profiles', 'ProfilesController#show');
profiles.blade.php
This is just a very simple page for now.
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<h1>{{ $user->user_id }}</h1>
<p>{{ $user->about_me }}</p>
</body>
</html>
Solution
I found an easy solution and I wanted to post it here to help others who might be struggling with creating a user profile page. The below assumes you already have a users table in your database and now you want to create a profiles table and connect user ID to their profile page.
Adding Laravel User Profiles
This is the video which help me.
Create table
php artisan make:migration create_profiles_table
This creates a migration file:
2019_09_22_213316_create_profiles_table
Open migration file and add extra columns you need:
$table->integer('user_id')->unsigned()->nullable();
$table->string('about_me')->nullable();
Migrate these to database
php artisan migrate
Now we have our database sorted, we need to create a controller to control how our php functions.
ProfilesController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class ProfilesController extends Controller
{
public function show($user_id)
{
$user = User::find(1);
$user_profile = Profile::info($user_id)->first();
return view('profiles.show', compact('profile', 'user'));
}
public function profile()
{
return $this->hasOne('Profile');
}
}
routes/web.php
Route::get('dashboard/profile', 'ProfilesController#show');
Profile.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Profile extends Model
{
public function user()
{
return $this->belongsTo('User');
}
}
Add this to User.php
public function profile()
{
return $this->hasOne('Profile');
}
profile.blade.php
Create any design you want. If you want to pull in users name, include {{ Auth::user()->name }}
try this
Route::get('pages/profiles/{id}', 'ProfilesController#show')->name('profiles.show');
Because in link you use a name route but in web.php there is no name route called profiles.show.so it's show error.And In Route You Need To pass the ID.
At Blade File :
link to your profile page
Change Route Style like below :
Route::get('pages/profiles/{id}', 'ProfilesController#show')->name('profiles.show');
At Profile Model
public function user()
{
return $this->belongsTo(User::class);
}
In Profiles.blade.php
<body>
<h1>{{ $profile->id }}</h1>
<p>{{ $profile->about_me }}</p>
</body>
You Passed User information through "profile" parameter. So you have to write this name in blade file.
Note Route Function won't work if you don't mentioned any name for this Route name. Either you have to use URL.
Your route is wrong, take a look at named routes. If you don't use Route::resource(), you have to manually name your routes and specify when you are expecting a parameter (in this case the profile ID).
Route::get('pages/profiles/{id}', 'ProfilesController#show')->name('profiles.show');
link to your profile page
Route model binding is probably the way to go in this case.
Route::get('pages/profiles/{profile}', 'ProfilesController#show')->name('profiles.show');
namespace App\Http\Controllers;
use App\Profile;
use Illuminate\Http\Request;
class ProfilesController extends Controller
{
public function show(Profile $profile)
{
return view('profiles.show', compact('profile'));
}
}
Im having an issue where this code just executes and the vardump shows the var i put in the text field but theres no data showing up in the database, theres also no error showing up
view:
<!DOCTYPE html>
<html>
<head>
<link href="https://fonts.googleapis.com/css?family=Lato:100" rel="stylesheet" type="text/css">
<body>
<div>
<form method="post" action="/post">
{{ csrf_field() }}
<input type="text" name="email">
<input type="text" name="password">
<input type="submit" name="submit">
</form>
</div>
</body>
</head>
</html>
controller:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\werknemer_model;
class werknemer extends Controller
{
/*Show the form for creating a new resource.*/
public function create(Request $request)
{
$email = $request->input('email');
var_dump($email);
$werknemer = new werknemer();
$werknemer->store($request);
return view('login_portal');
}
}
model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use App\controllers\werknemer
class werknemer_model extends Model
{
public function store (Request $request){
$email = $request->input('email');
$password = $request->input('password');
$werknemer = new werknemer;
$werknemer->id = 1;
$werknemer->bedrijf_id = 1;
$werknemer->email = $email;
$werknemer->naam = $password;
$werknemer->save();
try {
DB::connection()->getPdo();
} catch (\Exception $e) {
die("Could not connect to the database. Please check your configuration.");
}
}
}
Routes:
Route::get('/', function () {
return view('Login_portal');
});
Route::post('/post','werknemer#create');
Question : My data isnt being saved to database and im not getting an error
It is common problem, easy to forgot. You forgot to set variable in your model (for Mass Assignment). Check what data you want to put to database and set it in your model.
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Flight extends Model
{
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = ['name', 'another_data', 'another_variable'];
}
And as far as I see, your model structure is not going along the Laravel convention. Read it and save time in future: https://laravel.com/docs/5.6/eloquent#mass-assignment
I am customizing laravel 5's built in login so that it would redirect to three different paths according to the type column which i added to the users table, i tried altering the handle function of RedirectIfAuthenticated middleware. but it seems that it always finds the home URI.
here is my edited middleware
public function handle($request, Closure $next)
{
if ($this->auth->check() && $this->auth->user()->type == 'patient') {
// return redirect('/home');
return 'PATIENT VIEW';
} elseif ($this->auth->check() && $this->auth->user()->type == 'doctor') {
return 'DOCTOR VIEW';
} elseif ($this->auth->check() && $this->auth->user()->type == 'nurse') {
return 'NURSE VIEW';
}
return $next($request);
}
Im new to laravel 5 and i would really appreciate any help and explanations
RedirectIfAuthenticated is being misused here. That middleware is for when an authenticated user tries to access a page that should only be accessed by guests. For example, if I am a user and I try to view the login or registration forms, it doesn't let me.
I would not mess with the authentication itself... some of it is easily customizable but what you're trying to do is not. I would just let Laravel authenticate them first and then handle what to do after.
/home is the default route users are taken to when they login. Move your if checks to that route controller method. Better yet... if you set things up right you don't need any checks at all.
class HomeController {
public function index()
{
$user = \Auth::user();
return view($user->type . '.dashboard');
}
}
Now you just need views named patient/dashboard.blade.php, doctor/dashboard.blade.php, etc. If you have more complex logic then you might want an actual redirect
return redirect('home/' . $user->type);
Define routes for each of those types
Route::get('home/patient', 'PatientController#dashboard');
Route::get('home/doctor', 'DoctorController#dashboard');
Route::get('home/nurse', 'NurseController#dashboard');
And then do whatever you need to in those controller methods.
Check out the docs in Authentication section
Basically what you need is:
Create the auth routes at app/Http/routes.php:
// Authentication routes...
Route::get('auth/login', 'Auth\AuthController#getLogin');
Route::post('auth/login', 'Auth\AuthController#postLogin');
Create the login form view:
<!-- resources/views/auth/login.blade.php -->
<form method="POST" action="/auth/login">
{!! csrf_field() !!}
<div>
Email
<input type="email" name="email" value="{{ old('email') }}">
</div>
<div>
Password
<input type="password" name="password" id="password">
</div>
<div>
<input type="checkbox" name="remember"> Remember Me
</div>
<div>
<button type="submit">Login</button>
</div>
</form>
Manually Authenticate users app/Http/Controllers/Auth/AuthController.php:
<?php
namespace App\Http\Controllers;
use Auth;
use Illuminate\Routing\Controller;
class AuthController extends Controller
{
/**
* Handle an authentication attempt.
*
* #return Response
*/
public function authenticate()
{
if (Auth::attempt(['email' => $email, 'password' => $password])) {
if (Auth::user()->type == 'patient'){
return redirect()->intended('patientDashboard');
}
if (Auth::user()->type == 'doctor'){
return redirect()->intended('doctorDashboard');
}
}
}
}
Or if you want to keep the logic under RedirectIfAuthenticated middleware you could just fix your code:
public function handle($request, Closure $next)
{
if ($this->auth->check())
{
//we have a logged user check if it's patient
if($this->auth->user()->type == 'patient'){
return new RedirectResponse(url('/patient'));
}else if($this->auth->user()->type == 'doctor'){
return new RedirectResponse(url('/doctor'));
}
}
return $next($request);
}
Also you should check out this Entrust package.