retrieve database values in register page in laravel - laravel

I have registration auth in laravel project and i need some existing datas should show up on the registration form , please guide me up..
http://165.232.187.63/register
This is my register page and i need to fetch existing database values in the registration form. for example
<select>
#foreach($users as $items)
<option>{{ $items->id }}</option>
#endforeach
</select>
How to customize this...
I have tried adding in web.php file
Route::get('/register','App\Http\Controllers\Auth\UserController#index');
And in my UserController.php
public function index()
{
$users = User::all();
return view('auth.register')
->with('users', $users);
}
But can't use both post and get for register auth

You need to use separate endpoints for this task
one to load the view
Route::get('/register','App\Http\Controllers\Auth\UserController#index');
and the other to do the actual registration
Route::post('/register','App\Http\Controllers\Auth\UserController#register');
of course in the UserController, you will have a register method that handles the actual registration process

Related

Select option in Laravel, how to store in a database? [duplicate]

Hello i´m new in laravel. I dont know how to store the value of a select in a variable.
This is how i do it in php. But how in laravel?
Thank you for help :)
<?php
session_start();
//Database
$servername = "127.0.0.1";
$username = "root";
$password = "root";
//Connection to Database
$conn = new mysqli($servername, $username, $password);
//Connection Test
if(!$conn) {
echo "Not connected to Server"
}
if(!mysqli_select_db($conn, 'test')){
echo "No connection to Database";
}
//store data in variable
$vorname = $_POST['name'];
$name = $_POST['age'];
?>
<!--Form Select-->
<form action="test.php" method="post">
<select name="name">
<option value="Lisa"></option>
<option value="Laura"></option>
</select>
<select name="age">
<option value="20">20</option>
<option value="21">21</option>
</select>
<button type="submit">Sent</button>
</form>
<?php
$query = "SELECT * FROM test WHERE name = $name AND age = $age";
$profile = $conn->query($query);
?>
I want a Form with a select and the selected option should be stored in a variable.
Then checked in the database. And then show the results.
i dont know how to do thisin laravel.
thanks :)
All right let's get started. I suggest you study laravel documentation so things get more clear to you.
First of all you need to create your routes in your web.php file.
Route::get('/test', 'testController#index')->name('test.index');
Route::post('/values', 'testController#getValues')->name('test.values');
The first one will return your view the second one is to insert the data. Hang in there i will explain everything in the next lines.
Now you need a controller to handle the data and of course a view to preview your dropdowns.
In order to make a controller you can simple use php artisan make:controller testController command.
This will create a controller named testController like we named it in our routes.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use DB;
class testController extends Controller
{
public function index()
{
return view('test');
}
}
This is how your controller will look on this step. Simply return your view template (which i named it test for example pursposes). Now you actually need to create this view that you are trying to return. So inside the views file you create a test.blade.php file and post your html code a bit modified.
<form action="{{ action('testController#getValues') }}" method="post" id="postData">
{{ csrf_field() }}
<select name="name">
<option value="Lisa">Lisa</option>
<option value="Laura">Laura</option>
</select>
<select name="age">
<option value="20">20</option>
<option value="21">21</option>
</select>
<button type="submit">Sent</button>
</form>
You will notice that the action of the form is pointing straight to a controller function which will create in the next step. It's used to insert the data in the Database.
The csrf_field creates a token. For now you will realize that it helps your session not to "timeout" but does a lot more than that. Read more about it here!!!
The way to access your form is simple that's why laravel's routing makes things so simple. Go like "localhost/my_project_folder/test" and you should be able to see your view.
All right moving forward. Now you need to send the data from view to controller so you store it in the db.
We need a new function in the controller named getValues like we named it in the web.php file in the beginning. Now your controller should look like that:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use DB;
class testController extends Controller
{
public function index()
{
return view('test');
}
public function getValues(Request $request){
$name=$request->get('name');
$age=$request->get('age');
$insertData=DB::table('data')->insert(
['name' => $name, 'age' => $age]
);
}
}
Request method is really useful in laravel so investigate some more about this method here!!!
Now the final part. Connect your database. All the connections happen in the .env file.
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=testingdata
DB_USERNAME=root
DB_PASSWORD=root
This is my private database in my localhost so you can modify it using your credentials. After doing this step you are good to go.
If you have used different database or made a lot of changes etc etc and feel like you are using old settings run php artisan config:cache command to configure your cache with the latest changes.
This is the simplest walk through for insert data from the form to the database. You can optimize it and expand it a lot so my suggestion to you is to start reading laravel documentation, if possible get access to laracast and if you have time participate in the laracasts forum.

laravel resource controller store method not working for some users

I m using laravel 8 auth middleware on a group route and under that group route there are multiple resource routes.
Store method is not working for some users.
I have checked all possibility like csrf and trailing slash etc.
its posting data to index method for some users but for other users its working fine.
web.php
Route::name('')->middleware(['auth','CheckRole'])->group(function () {
//role routes
Route::resource('role', RoleController::class);
//role dumpsites
Route::resource('dumpsite', DumpsiteController::class);
});
controller --it large i cant add whole
public function store(Request $request){
$o = new Dumpsite;
$o->remarks = $request->post('remarks');
$o->save();
return redirect()->route('dumpsite.edit', ['dumpsite' => $o->id])->with('success', 'Submitted successfully');
}
view
<form enctype="multipart/form-data" action="{{route('dumpsite.store')}}" method="POST">

Laravel missing parameters to update form in controller

So I have a little project, in it, there's the possibility to upload banners images to be shown on the main page. All the stuff related to the DB are already created and the option to create a banner is working, it creates the banner and then stores the image on the DB for use later. Now I'm trying to work on an edit function so I can change the description under the bannners. I have an Edit route in my controller which returns a view where I edit said banner then it calls the update function on the controller. But no matter what I put here, I'm always getting the Missing Required Parameters error once I try to Save the edit and open my controller through the Update function. Here's the code as it is now:
The route definition:
Route::resource('banner', 'BannerController');
The edit function on my controller:
public function edit($id)
{
return view('admin/edit-banners',['id'=>$id]);
}
The update function has not been implemented because I always start with a dd() function to check if everything is working fine:
public function update(Request $request, $id)
{
dd($request);
}
And here's the form line in my edit view that is trying to call the update route:
<form class="card-box" action="{{ route('banner.update',[$banner]) }}">
I also added this at the beginning of the view to store the data from the DB into a variable:
#php
use\App\Banner;
$banner = Banner::where('id','=',$id)->get();
#endphp
The $banner variable contains all the information on the banner being edited, and I can get the new description at the controller with the $request variable, so I honestly don't know what should I put here as parameters, any ideas?
The $banner variable is not a Model instance, it is a Collection.
Adjust your controller to pass this to the view instead of dong the query in the view:
public function edit($id)
{
$banner = Banner::findOrFail($id);
return view('admin.edit-banners', ['banner' => $banner]);
}
You could also use Route Model Binding here instead of doing the query yourself.
Remove that #php block from your view.
The form should be adjusted to use method POST and spoof the method PUT or PATCH (as the update route is a PUT or PATCH route) and you should adjust the call to route:
<form class="card-box" action="{{ route('banner.update', ['banner' => $banner]) }}" method="POST">
#method('PUT')
If you include $id in your function declaration then when you call the route helper it expects you to give it an id parameter. Try with
<form class="card-box" action="{{ route('banner.update',['id' => $id]) }}">
You should be able to retrieve the form data just fine form the $request variable. More info here.
The code below should be the error source. $banner variable then is an array but the update function accept object or id.
#php
use\App\Banner;
$banner = Banner::where('id','=',$id)->get();
#endphp
You should try to replay this code by this one...
#php
use\App\Banner;
$banner = Banner::find($id);
//you should put a dd here to view the contain of $banner if you like
#endphp
Hop it help...

if else condition in routes laravel

I want only user with same name with the url id can access using if condition
Example
User logged on with name jer
He should only access url with /User-Profile/jer
And not access other page /User-Profile/abc that are not equal to his
name
Doing something like Example:
if{id}!=={{auth->name}}
{
Route::get('NoPermission', 'Restriction#index');
}
else
{
Route::get('/User-Profile/{name}/', 'AccountController#index');
}
How can I compare {name} from url to {auth->name} ?
Route
Route::get('/User-Profile/{name}/', 'AccountController#index');
Blade
<a href="/dashboard/User-Profile/{{ Auth::user()->name }}">{{ Auth::user()->name
}}</a>
You can't access Auth like that in your routes, compare it in your AccountController instead:
public function index($name){
if($name != Auth::user->name()) abort(403);
else...
}
In a service provider (Doesn't really matter which one, but it would be clearer if done in the RouteServiceProvider), add a route binding in the boot method as documented in https://laravel.com/docs/6.x/routing#explicit-binding
public function boot()
{
// Declare binding 'name'.
Route::bind('name', function ($name) {
return App\User::where('name', $name)->first() ?? abort(404);
});
}
Then, use that binding in your routes file
// Use binding name and middleware auth to make sure this route can't be accessed by guest users.
Route::get('/User-Profile/{name}/', 'AccountController#index')->middleware('auth')->name('account_profile');
In your blade file, you can do the following
{{-- Make sure the link is only visible for authenticated users https://laravel.com/docs/6.x/blade#if-statements --}}
#auth
<a href="{{ route('account_profile', ['name' => auth()->user()->name]) }}</a>
#endauth
Allow acces to the page , but before showing content ,check if the url path is == to the id name .
Actually, you can check in your routes like this:
Route::get('/profile/{name}', function(String $name) {
if (!Auth::check() || $name !== Auth::user()->name) {
abort(404);
}
return view("view.auth.profile", ['profile => App\Profile::where('user_id', '=', Auth::id())->first()]);
});
However if you use
Route::get('/profile', 'AuthController#profile')->middleware('auth');
and use Auth::user() in your controller to select the correct profile.
The benefit here is that any unauthenticated users will be automatically redirected to your login page, and there's no need to include the name on your profile link.

Compare route name in blade

I am using Laravel 5.2 and Blade templating, currently I am using this code to send the user to their own profile
href="{{ route('profile.index', ['username' => Auth::user()->username]) }}
This code is in an #if statement in blade, I was wondering how I would be able to check to make sure the user is on their own profile before I show them elements they should only be able to see on their own profile?
Just use check similar to this in your controller:
if (Auth::check()) // Checks if user authenticated
{
$userId = Auth::user()->id; // Gets user ID
// Do some stuff
}
return view('profile', compact('profileInfo'));
In this case any user will see only he's own profile.

Resources