I am new to web development and have been learning Laravel. I am following a video tutorial series (https://laracasts.com/series/laravel-5-from-scratch). In the series they use a text are to pass data to a post controller. I would like the user to input their name. If they are in the database, then they are taken to a user's page. I have the Model, database, and migrations working.
For the index page, routing:
Route::get('/','UserController#index');
Route::get('/user', UserController#checked');
Route::get('/accesdenied','UserController#accessdenied');
index view:
<h1>Welcome</h1>
<h1>Please enter User Name</h1>
<form>
<div>
<textarea name="body"></textarea>
<button type="submit">Access</button>
</div>
</form>
controller:
class UserController extends Controller
{
public function index()
{
return view('users.index');//view is in users folder
}
public function check(Request $request)
{
$user = DB::table('users')->where('name', $request->body)->first();
if (isset($user))
return view(‘users.checked’, compact(‘user’));
else
return view('users.accessdenied');//is it right to direct to a page back to a controller?
}
public function accessdenied(Request $request)
{
//try again is same as index page with text added
return view('users.tryagain');
}
}
I have no idea what to pass from the form.
Thank you.
just do a small change
<h1>Welcome</h1>
<h1>Please enter User Name</h1>
<form method="get" action="{{ action('UserController#checked') }}">
<div>
<textarea name="body"></textarea>
<button type="submit">Access</button>
</div>
</form>
Related
profile.blade.php
<form action="{{route('user.profile.update',$user)}}" method="post" enctype="multipart/form-data">
#csrf
#method('PUT')
<div>
<img height="100px;" class="img-profile rounded-circle" src="{{$user->avatar}}">
</div>
<br>
<div class="form-group">
<input type="file" name="avatar">
</div>
</form>
web.php
Route::put('admin/users/{user}/update','UserController#update')->name('user.profile.update');
User.php
public function getAvatarAttribute($value){
return asset($value);
}
UserController:
public function update(User $user){
$inputs=request()->validate([
'file'=>['file'],
]);
if(request('avatar')){
$inputs['avatar']=request('avatar')->store('images');
}
$user->update($inputs);
return back();
}
}
This is a profile.blade.php
How to display the image from the public/storage/images in Laravel
If I inspect the image the src is src="http://127.0.0.1:8000/images/dT9gvraL3HbTlHcQly96YwoSJdikNj7fVL1dsIzT.jpeg". How did I do wrong?
Considering that you are storing images with name not with url.
Now, in User.php,
public function getAvatarAttribute($value){
return asset('storage/'.$value);
}
Hope this will help you.
My bad, I skipped some parts of your question. You need to change the path in User.php as following:
public function getAvatarAttribute($value){
return asset("storage/$value");
}
To get accessible url for public URLs. Laravel provides asset helper for the same.
For example if your image is stored in
public/storage/image/user.png
You can easily access the image like below:
asset('storage/image/user.png') //outputs complete url to the file
Note: public folder is considered as base directory.
I'm learning Laravel and I got stuck trying to get data from a form.
I already am able to get data back with GET, but with POST I've been having a ton of trouble. Here's what I'm working with:
Form:
<form id="forms" method="POST" action="sugestoes" novalidate>
{{ csrf_field() }}
<div class="form-row">
<div class="form-group col-md-12">
<label for="obs">Observações:</label>
<textarea type="text" class="form-control" name="obs" placeholder="Observações" required></textarea>
</div>
</div>
<hr>
<button type="submit" class="btn btn-primary">Enviar</button>
</form>
#php
if (isset($_POST["obs"])) {
echo "IN";
}
#endphp
Controller:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class PostController extends Controller
{
public function store(Request $request)
{
$name = $request->input('obs');
return redirect('sugestoes');
//
}
}
Route:
Route::post('sugestoes', 'PostController#store');
The intended behaviour that I'm trying to reach is for the post to be submitted, and then returning to the same page with an empty form. Later on I'll be sending the input data into a database, but for now I just want to get the post to work.
I guess I'm missing something really basic, but I've been following guides and looking online, I've done some progress but I'm really stuck here.
(some more info, this is Laravel 5.4, and I'm using XAMPP)
First, you need to call the model, use App/Your_model_name; then you have to save the data.
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Suggest; //Suggest model, let's hope you have suggest table
class PostController extends Controller
{
public function store(Request $request)
{
$suggest = new Suggest; //model
$suggest->name = $request->obs; //name is DB name, obs is request name
$suggest->save(); //save the post to DB
return redirect()->back()->with('success', 'Saved successfully'); //return back with message
}
}
Then if you want to flash the message on the HTML page
#if(session('success'))
<div class="alert alert-warning alert-dismissible" id="error-alert">
<strong style="color: white;">{{session('success')}}</strong>
</div>
#endif
<form id="forms" method="POST" action="{{ route('sugestoes') }}" novalidate>
{{ csrf_field() }}
<div class="form-row">
<div class="form-group col-md-12">
<label for="obs">Observações:</label>
<textarea type="text" class="form-control" name="obs" placeholder="Observações" required></textarea>
</div>
</div>
<button type="submit" class="btn btn-primary">Enviar</button>
</form>
Remove the #php tag below the form, then in router.php
Route::post('/sugestoes', 'PostController#store')->name('sugestoes');
Then in Controller:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class PostController extends Controller
{
public function store(Request $request)
{
$name = $request->input('obs');
return redirect('/sugestoes'); // you should have GET in Route.php
//
}
}
Add the following code in your action attribute on the form. It will capture the post URL. When you submit the form it will send the form data to the URL end-point.
action="{{ url('sugestoes')}}"
Then die and dump in your controller store function
public function store(Request $request)
{
dd($request->all());
}
I have a simple input form with a text input field and a submit button. I am trying to get the value from the input field to be displayed again on the same page after the submit button is clicked. So far laravel always throws an error that the variable is undefined.
Route:
Route::get('/find/names', "FindController#get_name")->name('names');
Controller
public function get_name(){
$name = Input::get('name_by_user');
return $name;
}
view
<form role="form" method="GET">
<div class="row">
<div class="form-group">
<div class="input-group">
<input type="text" name="name_by_user"/>
<span class="input-group-btn">
<button class="btn search-button" type="submit">
<span aria-hidden="true">
<span>Search</span>
</button>
</span>
</span>
</div>
</div>
</div>
</form>
display name after submitting: {{$name}}
I would do something like this
Route
Route::name('names')->get('/find/names', "FindController#get_name");
Controller
public function get_name(){
$collection = Input::all();
$name = $collection->pluck('name_by_user');
return view('view_file_in_resources', compact('name'));
}
Now you will have a $names collection in your view.
But if you only want to fetch result from one row, you controller should look like this:
public function get_name($name){
$name = Input::where('name_by_user', $name)->get();
return view('view_file_in_resources', compact('name'));
}
And your routes file
Route::name('names')->get('/find/names/{name}', "FindController#get_name");
When generating a view inside a controller for a route, you can do the following in a function to return a view with data depending on whether it exists.
public function showNameView() {
if(is_null(Input::get('name_by_user'))
{
return view('my.view')->with(['name' => Input::get('name_by_user')]);
}
else
{
return view('my.view')->with(['name' => Input::get('name_by_user')]);
}
}
You need to return the same view:
public function get_name(Request $request)
{
return view('same.view', ['name' => $request->name]);
}
Or you can redirect back:
return redirect()->back()->with('name', $request->name);
And display name like using session data:
#if (session()->has('name'))
{{ session('name') }}
#endif
I have problem to save name and email from user1 in table user1s that I have made .
When I enter them in textareas using html form in Laravel with route::post and function store it is not working. When I enter text and hit the button Register it outputs the following error:
MethodNotAllowedHttpException in RouteCollection.php line
You will see that I use the HTML form and that I have tried to add <input ....> into my form.
Here are my files:
route.php
<?php
Route::get('/','PageController#home');
Route::post('/','User1Controller#store');
Route::get('about','PageController#about');
welcome.blade.php
I'm not sure about the action.
After putting user1 inf into table, it should be redirected to a "Thank you" page (I have a thankyou.blade.php ) , maybe that is the problem
<form method="POST" action="">
<input name="_token" type="hidden" value="{{ csrf_token() }}"/>
<ul class="list-group" >
<li >
NAme
<div class="form-group" title="email" >
<textarea name="name" class="form-control" >
</textarea>
</div>
</li >
<li>Email
<div class="form-group" >
<textarea name="email" class="form-control" >
</textarea>
</div>
</li>
<li >
<div class="form-group" >
<button class="btn btn-primary">Register</button>
</div>
</li>
</ul>
</form>
migration for user1
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateNotesTable extends Migration
{
public function up()
{
Schema::create('notes', function (Blueprint $table) {
$table->increments('id');
$table->integer('card_id')->unsigned();
$table->text('body');
$table->timestamps();
});
}
public function down()
{
Schema::drop('notes');
}
}
user1controller.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\User1;
class User1Controller extends Controller
{
public function store(Request $request)
{
$user= new User1;
$user->name = $request->name;
$user->email = $request->email;
$user->save();
return view('thankyou');
}
}
pagecontroller.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\User1;
class PageController extends Controller
{
public function home()
{
$user1s= User1::all();
return view('welcome',compact('user1s'));
}
public function about()
{
return view('pages.about');
}
}
Your form is basically a registration form. I would recommend using a more meaningful name for the end point. The post route can be something like,
Route::post('/register','User1Controller#store');
Now the form action can be,
action="/register"
I corrected the typo.Thanks!
I have also changed this
Route::post('/','User1Controller#store');
and action=" " .
It works ,the only thing right now that is not good is that I should redirect to a page "Thank you" not go to anther view on the exact same page.
Because It makes a mess in the database when I reload the home page.
I'll try that and tell if it works.
Thank you people for the help! :)
Things solved,this works. I will add the code that i have added so the other can find it!
Firs of all : I haven't figured why ,but action="dir1/dir3" for me didn't work!
Here are the added things!
routes.php
Route::get('thankyou','PageController#thankyou');
***PageController.php***
public function thankyou()
{
return view('thankyou');
}
*****User1Controller.php*****
public function store(Request $request)
{
$user= new User1;
$user->name = $request->name;
$user->email = $request->email;
$user->save();
return redirect('/thankyou');
}
I am new to CodeIgniter. I need to process a form. I have a form.html page in view
<html>
<head>
<title>Search</title>
</head>
<body>
<form action="search">
<input type="text" name="search" value="" size="50" />
<div>
<input type="submit" value="Submit" />
</div>
</form>
</body>
</html>
and form controller
class Form extends Controller {
function Form() {
parent::Controller();
}
function index() {
$this->load->view('form');
}
}
and I have an view file search.php but when it is processed it shows page not found...
In M.odel V.iew C.ontroller setups like CodeIgniter the Views are user interface elements. They should not be parsing results.
If I am not mistaken, what you are looking to do is pass data from www.yoursite.com/index.php/form to www.yoursite.com/index.php/search
In unstructured php you might have a form.html with a form action of search.php. A user would navigate to yoursite.com/form.html, which would call yoursite.com/search.php, which might redirect to yoursite.com/results.php.
In CodeIgniter (and, as far as I understand it, in any MVC system, regardless of language) your Controller, Form calls a function which loads the form.html View into itself and then runs it. The View generates the code (generally HTML, but not necessarily) which the user interacts with. When the user makes a request that the View cannot handle (requests for more data or another page) it passes that request back to the Controller, which loads in more data or another View.
In other words, the View determines how the data is going to be displayed. The Controller maps requests to Views.
It gets slightly more complicated when you want to have complex and / or changing data displayed in a view. In order to maintain the separation of concerns that MVC requires CodeIgniter also provides you with Models.
Models are responsible for the most difficult part of any web application - managing data flow. They contain methods to read data, write data, and most importantly, methods for ensuring data integrity. In other words Models should:
Ensure that the data is in the correct format.
Ensure that the data contains nothing (malicious or otherwise) that could break the environment it is destined for.
Possess methods for C.reating, R.eading, U.pdating, and D.eleting data within the above constraints.
Akelos has a good graphic laying out the components of MVC:
(source: akelos.org)
That being said, the simplest (read "easiest", not "most expandable") way to accomplish what you want to do is:
function Form()
{
parent::Controller();
}
function index()
{
$this->load->view('form');
}
function search()
{
$term = $this->input->post('search');
/*
In order for this to work you will need to
change the method on your form.
(Since you do not specify a method in your form,
it will default to the *get* method -- and CodeIgniter
destroys the $_GET variable unless you change its
default settings.)
The *action* your form needs to have is
index.php/form/search/
*/
// Operate on your search data here.
// One possible way to do this:
$this->load->model('search_model');
$results_from_search = $this->search->find_data($term);
// Make sure your model properly escapes incoming data.
$this->load->view('results', $results_from_search);
}
View file is useless without the controller to load and displaying it. You must create a controller to receive the form data, process it, then displaying the process result.
You can use a form helper to set the form open tags, also the close tags:
<?php echo form_open('form/search'); ?>
<input type="text" name="search" value="" size="50" />
<div><input type="submit" value="Submit" /></div>
<?php echo form_close(); ?>
Without using form helper, you can still write it this way:
<form action="<?php echo site_url('form/search'); ?>">
Then add the search method into form controller:
function search()
{
//get form field
$search = $this->input->post('search');
// do stuffs here
//...
}
Remember that CI only help you with the basic code organization and provide a helpful library and helper. But you still need to write the algorithm of the process in your site.
Don't forget to read the included user guide in the downloaded codeigniter package. You can learn many stuffs from the example in there. Don't hesitate to ask things you don't know here, many member of stackoverflow will help you.
This is form validation and submit in controller
My whole controller class
class MY_Controller extends CI_Controller {
function __construct()
{
parent::__construct();
$this->load->library(array('session','form_validation'));
$this->load->helper(array('form', 'url', 'date'));
//$this->load->config('app', TRUE);
//$this->data['app'] = $this->config->item('app');
}
}
<?php
if (!defined('BASEPATH'))
exit('No direct script access allowed');
class Article extends MY_Controller {
function __construct() {
parent::__construct();
$this->load->model('article_model');
}
public function index() {
$data['allArticles'] = $this->article_model->getAll();
$data['content'] = $this->load->view('article', $data, true);
$this->load->view('layout', $data);
}
public function displayAll() {
$data['allArticles'] = $this->article_model->getAll();
$data['content'] = $this->load->view('displayAllArticles', $data, true);
$this->load->view('layout', $data);
}
public function displayArticle($id) {
$data['article'] = $this->article_model->read($id);
$data['articleId'] = $id;
$data['comment'] = $this->load->view('addComment', $data, true);
$data['content'] = $this->load->view('displayArticle', $data, true);
$this->load->view('layout', $data);
}
public function add() {
$this->form_validation->set_message('required', '%s is required');
$this->form_validation->set_rules('title', 'Title', 'required|xss_clean');
$this->form_validation->set_rules('description', 'Description type', 'required|xss_clean');
$this->form_validation->set_error_delimiters('<p class="alert alert-danger"><a class="close" data-dismiss="alert" href="#">×</a>', '</p>');
if ($this->form_validation->run() == TRUE) {
$article = array(
'title' => $this->input->post('title'),
'description' => $this->input->post('description'),
'created' => date("Y-m-d H:i:s")
);
$this->article_model->create($article);
redirect('article', 'refresh');
} else {
$data['article'] = array(
'title' => $this->input->post('title'),
'description' => $this->input->post('description'),
);
$data['message'] = validation_errors();
$data['content'] = $this->load->view('addArticle', $data, true);
$this->load->view('layout', $data);
}
}
}
We can use normal html form like this.
<?php echo $message; ?>
<form method="post" action="article/add" id="article" >
<div class="form-group">
<label for="title">Article Title</label>
<input type="text" class="form-control" id="title" name="title" value="<?php echo $article['title']; ?>" >
</div>
<div class="form-group">
<label for="description">Description</label>
<textarea class="form-control" rows="13" name="description" id="description"><?php echo $article['description']; ?></textarea>
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
</div>
</div>
Try using the codeigniter 'site_url' in your action to make sure you are pointing to the right place. The action in your example would have gone to the 'search' controller rather than the 'form' controller.
<html>
<head>
<title>Search</title>
</head>
<body>
<form action="<?= site_url('form/process_search') ?>">
<input type="text" name="search" value="" size="50" />
<div><input type="submit" value="Submit" /></div>
</form>
</body>
</html>
index is only used in your controller when nothing else is passed.. So in the case of my example above you would want something like this:
function Form()
{
parent::Controller();
}
function process_search()
{
print "<pre>";
print_r($_POST);
print "</pre>";
}
Nettuts has a great tutorial for CodeIgniter for Login form. Follow the screencast and it will clear up your questions.
http://net.tutsplus.com/videos/screencasts/codeigniter-from-scratch-day-6-login/
replace this <form action="search"> with <?php echo form_open('form/search');?>
and autoload.php file add $autoload['helper'] = array('form');
and then file dont use file search.php just add your search.php code into your Controller file
like here
class Form extends Controller {
function Form() {
parent::Controller();
}
function index() {
$this->load->view('form');
}
function search(){
//your code here
}
}