laravel-5.7: data is not saving into database, Object not found - laravel

I'm trying to save data into db but its not saving and says that object not found, can anyone suggest me solution, i am following this tutorial: https://laracasts.com/series/laravel-from-scratch-2018/episodes/10
controller:
public function index()
{
$projects = Project::all();
return view('projects.index', compact('projects'));
}
public function create()
{
return view('projects.create');
}
public function store()
{
$project = new Project();
$project->title = request('title');
$project->description = request('description');
$project->save();
return redirect('/projects');
}
routes:
Route::get('/projects','ProjectsController#index');
Route::post('/projects','ProjectsController#store');
Route::get('/projects/create','ProjectsController#create');
create.blade.php:
<form method="POST" action="/projects">
{{ csrf_field() }}
<div>
<input type="text" name="title" placeholder="Project title">
</div>
<div>
<textarea name="description" placeholder="Project description"></textarea>
</div>
<div>
<button type="submit">Create Project</button>
</div>
</form>
index.blade.php:
#foreach($projects as $project)
<li>{{ $project->title }}</li>
#endforeach

You have missed out passing request parameter in the controller store()
public function store(Request $request)
{
$project = new Project();
$project->title = $request->title;
$project->description = $request->description;
$project->save();
return redirect('/projects');
}
And also don't forget to include use Illuminate\Http\Request; above(outside) controller class.

The Laravel code you've posted is correct under a properly configured website. The error from your comments:
Object not found! The requested URL was not found on this server. The
link on the referring page seems to be wrong or outdated. Please
inform the author of that page about the error. If you think this is a
server error, please contact the webmaster. Error 404 localhost
Apache/2.4.33 (Win32) OpenSSL/1.1.0h PHP/7.2.7
is an Apache error page, which means it's not requesting a page from your laravel project at all. The data is probably saving in your database, but then you redirect away to a page that is outside your project, and Apache can't find it.
Your website is located at http://localhost/laravel/public, which means you need to access the projects page at http://localhost/laravel/public/projects. However, redirect('/projects') gives you an absolute path instead of a relative path, sending you to http://localhost/projects, which does not exist.
Solutions
Since this is a local development project, I'm going to skip the issues with the improper Apache configuration and focus on other ways to avoid the error.
Option 1
Use a named route:
Route::get('/projects','ProjectsController#index')->name('projects.index');
and use the name of the route for the redirect:
return redirect()->route('projects.index');
This should generate correct urls within your project.
Option 2
Use serve for development instead of Apache.
Open a terminal in your Laravel project directory and run this command:
php artisan serve
This will start PHP's built-in webserver at http://localhost:8000, skipping Apache entirely. During development this is perfectly fine.

Related

Fail to retrieve Post data with Laravel

I try to learn Laravel (v.9) from scratch but fail to do a simple basic task:
I just want to send "post_var" by POST request and display the var.
My form (blade template):
<form action="/post_and_show" method="POST">
#csrf
#method('post')
<input type="text" name="post_var">
<input type="submit" value="send">
</form>
My Route (in web.php) with some dd() i tried to find the problem
Route::post('/post_and_show', function (Request $request) {
dd($request->method()); // returns GET ?? !!
// chrome debugger network tab show clearly its a POST request...
dd($request->all()); // returns empty Array
dd($request->post_var); // returns null
dd($request->getContent()); // returns string but i want param only
// "_token=yBBYpQ303a1tSiGtQF6zFCF6p6S7qadVfHMk4W7Q&_method=post&post_var=12345"
});
What am i doing wrong here?
Tried several methods i found in the documentation but non worked so far.
EDIT: I removed "#method('post')"
Btw.: My initial version that did not work either had no "#method('post')". I added it later on in the hope it might help...
<form action="/post_and_show" method="POST">
#csrf
<input type="text" name="post_var">
<input type="submit" value="send">
</form>
But have still the same problems:
Route::post('/post_and_show', function (Request $request) {
dd($request->method()); // returns GET ?? !! but chrome says its a post request
dd($request->post_var); // returns null
dd($request->get('post_var'));// returns null
dd($request->getContent()); // returns complete body and header in one string
dd($request->all()); // return empty Array
});
EDIT 2:
Googleing i found "createFromGlobals":
use Illuminate\HTTP\Request; // just added this to show which class i use here...
use Illuminate\Support\Facades\Route;
Route::post('/post_and_show', function () {
dd(Request::createFromGlobals()->get('post_var')); // returning expected value
});
This works for me, but i can't find this method in documentation. Sorry, i am new to laravel and even php, so this seems all completely crazy to me.. ;-)
EDIT 3:
If i use a simple Controller it works too...
Controller:
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class FormController extends Controller
{
public function show(Request $request)
{
dd($request->post_var); // returns expected value...
}
}
Route:
Route::post('post_and_show', [FormController::class, 'show']);
So only in case i use the $request immediatly in the callback it does not work as expected. ( Either by design or bug??)

Laravel 8 Flash Session not working on Request

I wonder in my application can't show flash message. I have tried many solutions on stackoverflow but my problem is not solved.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redirect;
class DebugController extends Controller
{
public function get()
{
// Visit direct page flash session is working
// Eg: localhost/debug/get
// But if I send request all flash sessions are not working
return Redirect::route('home')->with('success', 'Working session on visit direct page!');
}
public function post(Request $request)
{
// All flash sessions are not working
session()->flash('anything', 'Session not working!');
// Working session
session()->put('message', 'Working session!');
// Session not working, is 'success' key reserved?
session()->put('success', 'Session not working!');
return Redirect::route('home')->with('anything', 'Session not working!'); // Session not working
}
}
Route:
Route::get('debug/get', 'DebugController#get');
Route::post('debug/post', 'DebugController#post');
View:
#if(Session::has('success'))
<div class="alert alert-success">
{{ Session::get('success') }}
</div>
#endif
// Working session
#if(Session::has('message'))
<div class="alert alert-success">
{{ Session::get('message') }}
</div>
{{ session()->forget('message') }}
#endif
I have tried to modify middle ware in Kernel from this solution but still not working
Laravel Version: 8.x.x
PHP Version: 7.4.x
You will need to do Session::has('anything') in your view instead of Session::has('success').
The first parameter is the key that can be accessed with has or get.
If the above is already done, you might need to use the Facade: Session::flash('anything','content');
Take a look at this.
In case you want to remove the Session data
you have to use flush instead of flash().
Laravel documentation

Laravel route returning error 404 when attempt is made to pass value to controller function

I have a button in my blade like this
#can('customer_show')
<a class = "btn btn-primary" href = "{{ route('admin.loan-applications.showCustView', $loanApplication->user_id) }}">
View Applicant
</a>
#endcan
And this is the route:
Route::get('loan-applications/{loan_application}/showCustView', 'loanApplicationsController#showCust')->name('loan-applications.showCustView');
And in my controller, i did:
public function showCust(LoanApplication $loanApplication)
{
$customerInformation = customerInfoModel::where('Cust_id', $loanApplication->user_id));
return view('admin.loanApplictions.showCustView', compact(['customerInformation', 'loanApplication']));
}
What i am trying to do is fetch the row from the database attached to customerInfoModel where the the Cust_id field equals the loanApplication->user_id of the loan being viewed currently in the blade above. When the button "view Applicant" is hit, i get an error 404 page. Why is that so?
Check it out the route list using this command
php artisan route:list
//this command will show all the routes in your application
If your route not listed on that route list checkout for routes with same Url on your route manually on routes file.
if you found change the url & use this command to clear cache
php artisan optimize:clear
i have found the comment of you on last answer.
check out for route model binding . i think you have to add
a
public function showCust( $loanApplicationCustId)
{
$customerInformation = customerInfoModel::where('Cust_id', $loanApplicationCustId))->first();
return view('admin.loanApplictions.showCustView', compact(['customerInformation', 'loanApplication']));
}
It should be like this .. i hope it works for you......
else share your project git repo link
I think it should be like following:
#can('customer_show')
<a class = "btn btn-primary" href = "{{ route('loan-applications.showCustView', $loanApplication->user_id) }}">
View Applicant
</a>
#endcan
try that

Undefined variable on Laravel

I´m a beginner starting with Laravel. I´m trying to show a question made on this website.
Here is the Controller page:
public function show($id)
{
//Use the model to get 1 record from the database
$question = $Question::findOrFail($id);
//show the view and pass the record to the view
return view('questions.show')->with('question', $question);
}
I have included at the top of the file:
use App\Question;
Here is my blade page:
#section('content')
<div class="container">
<h1> {{ $question->title }} </h1>
<p class="lead">
{{ $question->description }}
</p>
<hr />
</div>
#endsection
In the model I have not defined anything since I don´t need to specify any special rule. And finally here is the Route:
Route::resource('questions', 'QuestionController');
I got the error "ErrorException Undefined Variable: Question" and supposedly the error is on:
$question = $Question::findOrFail($id);
I´m looking forward to your observations.
Kind Regards.
You just need to change the controller section
public function show($id)
{
//Use the model to get 1 record from the database
$question = Question::findOrFail($id); // here is the error
//show the view and pass the record to the view
return view('questions.show')->with('question', $question);
}
Explanation:- You are going to use a variable $Question that is not defined. This is the basic PHP error, not the laravel issue.
However, You are using the "App\Question" model class not a sperate variable.

newbie problems with codeigniter

i'm trying to learn codeigniter (following a book) but don't understand why the web page comes out empty.
my controller is
class Welcome extends Controller {
function Welcome()
{
parent::Controller();
}
function index()
{
$data['title'] = "Welcome to Claudia's Kids";
$data['navlist'] = $this->MCats->getCategoriesNav();
$data['mainf'] = $this->MProducts->getMainFeature();
$skip = $data['mainf']['id'];
$data['sidef'] = $this->MProducts->getRandomProducts(3, $skip);
$data['main'] = "home";
$this->load->vars($data);
$this->load->view('template');
}
the view is:
<--doctype declaration etc etc.. -->
</head>
<body>
<div id="wrapper">
<div id="header">
<?php $this->load->view('header');?>
</div>
<div id='nav'>
<?php $this->load->view('navigation');?>
</div>
<div id="main">
<?php $this->load->view($main);?>
</div>
<div id="footer">
<?php $this->load->view('footer');?>
</div>
</div>
</body>
</html>
Now I know the model is passing back the right variables, but the page appears completely blank. I would expect at least to see an error, or the basic html structure, but the page is just empty. Moreover, the controller doesn't work even if I modify it as follows:
function index()
{
echo "hello.";
}
What am I doing wrong?
Everything was working until I made some changes to the model - but even if I delete all those new changes, the page is still blank.. i'm really confused!
thanks,
P.
I've isolated the function that gives me problems.
here it is:
function getMainFeature()
{
$data = array();
$this->db->select("id, name, shortdesc, image");
$this->db->where("featured", "true");
$this->db->where("status", "active");
$this->db->orderby("rand()");
$this->db->limit(1);
$Q = $this->db->get("products");
if ($Q->num_rows() > 0)
{
foreach($Q->result_arry() as $row)
{
$data = array(
"id" => $row['id'],
"name" => $row['name'],
"shortdesc" => $row['shortdesc'],
"image" => $row['image']
);
}
}
$Q->free_result();
return $data;
}
I'm quite convinced there must be a syntax error somewhere - but still don't understand why it doesn't show any error, even if I've set up error_reporting E_ALL in the index function..
First port of call is to run php -l on the command line against your controller and all the models you changed and then reverted.
% php -l somefile.php
It's likely that there is a parse error in one of the files, and you have Display Errors set to Off in your php.ini. You should set Display Errors on for development and off for production, in case you haven't already.
(Edit: in the example above you have missed off the closing } of the class. It might be that.)
Make sure error_reporting in index.php is set to E_ALL and post your code for the model in question.
After looking through your function I suspect it's caused by $this->db->orderby("rand()");
For active record this should be $this->db->order_by('id', 'random');
Note that orderby is deprecated, you can still use it for now but the new function name is order_by
Not sure, but it can be also caused by php's "display_errors" is set to false.
You can change it in your php.ini file.

Resources