Laravel 9 how to pass parameter in url from one controller to another controller? - laravel

I was facing this problem of missing parameter when trying to pass a parameter from one controller to another controller. The parameter is $id whereby the data is originally from post method in details blade.php into function postCreateStepOne However, I want to pass the data into a new view and I return
redirect()->route('details.tenant.step.two')->with( ['id' => $id]
);}
And this is where error occur. However, it works fine if I skip it into a new route and directly return into a view with the compact parameter. For Example,
return view('document.details-step-two', compact('id', 'property'));
However, I would prefer a new url as I was doing multistep form using Laravel.
Error
web.php
Route::get('/document/details/viewing/{id}', 'ViewDetails')->name('details.tenant');
Route::post('/document/details/viewing/{id}', 'postCreateStepOne')->name('post.step-one');
Route::get('/document/details/viewing/step-2/{id}', 'ViewDetailsStep2')->name('details.tenant.step.two');
TenanatController.php
public function viewDetails($id){
$view = Properties::findOrFail($id);
return view('document.details', compact('view'));
}
public function ViewDetailsStep2(Request $request, $id){
$view = Properties::findOrFail($id);
$property = $request->session()->get('property');
return view('document.details-step-two', compact('view', 'property'));
}
public function postCreateStepOne($id, Request $request)
{
$validatedData = $request->validate([
'property-name' => 'required',
]);
if(empty($request->session()->get('property'))){
$property = new Tenancy();
$property->fill($validatedData);
$request->session()->put('property', $property);
}else{
$property = $request->session()->get('property');
$property->fill($validatedData);
$request->session()->put('property', $property);
}
return redirect()->route('details.tenant.step.two')->with( ['id' => $id] );
}
details.blade.php
<form action="{{ route('post.step-one', $view->id) }}" method="POST">
#csrf
<div class="card-body">
<div class="form-group">
<label for="title">Property Name:</label>
<input type="text" value="" class="form-control" id="property-name" name="property-name">
</div>
</div>
<div class="card-footer text-right">
<button type="submit" class="btn btn-primary">Next</button>
</div>
</form>

When you use with on a redirect the parameter is passed through the session. If you want to redirect to a route with a given route parameter you should pass that parameter in the route function itself like e.g.
return redirect()->route('details.tenant.step.two', ['id' => $id]);

Related

Set "custom" withErrors without Request->validation in Laravel

I want to display an error in a form, but it cannot be checked via validation.
Blade
<form action="/githubuser" methode="GET">
<div class="error">{{ $errors->first('CustomeError') }}</div>
<input type="text" name="userName" placeholder="GitHub Username ..." value="John12341234">
#if($errors->has('userName'))
<div class="error">{{ $errors->first('userName') }}</div>
#endif
<input type="submit" value="SUBMIT">
</form>
The Problem is that I start an api call after validation. and if I don't get "GitHubUser" as a response, I want to print an error message in the blade. GitHub user not found.
Controller
public function show(Request $request)
{
$rules = ['userName' => 'required'];
$validator = \Validator::make($request->input(), $rules);
if ($validator->fails()) {
return redirect('/')
->withErrors($validator)
->withInput();
}
$data = $this->gitHubUserService->getUserData($request->input('userName'));
/* User on Github not Found **/
if (! $data) {
// >>> THE LINE BELOW IS MY PROBLEM! <<<
return view('form')->withErrors($validator);
}
// ....
}
At the end of the day I want the line <div class="error">{{ $errors->first('CustomeError') }}</div> to be displayed in the blade.
Is this possible? Thanks in advance!
The original validator is not getting any error, because there are none. So, just add a new error to the errors inside of your if body before returning form view:
if(! $data){
$validator->errors()->add('customError', 'Github User not found!');
return view('form')->withErrors($validator);
}

Route [tasks.complete] not defined. (View: /Users/pathparakh/Projects/task/resources/views/tasks/index.blade.php)

This is my TaskController where complete() function is defined to store done_at current time
public function complete($id)
{
$task = Task::create([
'done_at' => now(),
]);
return redirect()->route('tasks.index')->withSuccess('Done');
}
This is my web.php route
Route::post('/tasks/complete', 'TaskController#complete');
This is my index page where there is submit button to save current time
<form action="{{ route('tasks.complete', $task->id) }}" method="post">
#csrf
<input type="submit">
</form>
You missed name declaration of your route, like this:
Route::post('/tasks/complete', 'TaskController#complete')->name('tasks.complete');
Note: If you want to add new task use the first one, but if you want to update an existing task use the second one:
//---First:
TaskController:
public function complete() {
$task = Task::create([
'done_at' => now(),
]);
return redirect()->route('tasks.index')->withSuccess('Done');
}
web.php
Route::post('/tasks/complete', 'TaskController#complete')->name('tasks.complete');
Your view file(index page):
<form action="{{ route('tasks.complete') }}" method="post">
#csrf
<input type="submit">
</form>
//---Second:
Or if you need to pass the id parameter in your controller you should use the below code:
TaskController:
public function complete($id) {
$task = Task::findOrFail($id);
if ($task) {
$task->update([
'done_at' => now()
]);
return redirect()->route('tasks.index')->withSuccess('Done');
}
return redirect()->route('tasks.index')->withSuccess('Task No Found');
}
web.php
Route::post('/tasks/complete/{id}', 'TaskController#complete')->name('tasks.complete');
Your view file(index page):
<form action="{{ route('tasks.complete', ['id' => $task->id]) }}" method="post">
#csrf
<input type="submit">
</form>
As per your complete() function in the controller and as per the form action,
Your route should look like this:
Route::post('/tasks/complete/{id}', 'taskcontroller#complete')->name('tasks.complete');

Update data in laravel 6

I try to create crud in laravel 6. Create, Read and Delete process is running well. But when Update process, the data in table not change. Could anyone help me to find the problem ? The following my code.
Route
Route::get('/blog', 'BlogController#index');
Route::get('/blog/add','BlogController#add');
Route::post('/blog/store','BlogController#store');
Route::get('/blog/edit/{id}','BlogController#edit');
Route::post('/blog/update','BlogController#update');
Controller
public function index()
{
$blog = DB::table('blog')->get();
return view('blog',['blog' => $blog]);
}
public function edit($id)
{
$blog = DB::table('blog')->where('blog_id', $id)->get();
return view('edit', ['blog'=>$blog]);
}
public function update(Request $request)
{
DB::table('blog')->where('blog_id',$request->blog_id)->update([
'blog_title' => $request->title,
'author' => $request->author]);
return redirect('/blog');
}
View
#foreach ($blog as $n)
<form method="post" action="/blog/update" />
{{ csrf_field() }}
Title <input type="text" name="title" value="{{ $n->title}}">
Author<input type="text" name="author" value="{{ $n->author}}">
<button type="submit" class="btn btn-secondary">Update</button>
</form>
#endforeach
You must provide id in your route
Route::post('/blog/update/{id}','BlogController#update');
In update method add parameter id and then find product against id
public function update(Request $request, $id)
{
DB::table('blog')->where('blog_id',$id)->update([
'blog_title' => $request->title,
'author' => $request->author]);
return redirect('/blog');
}
#foreach ($blog as $n)
<form method="post" action="{{ route('your route name'), ['id' => $$n->id] }}" />
{{ csrf_field() }}
Title <input type="text" name="title" value="{{ $n->title}}">
Author<input type="text" name="author" value="{{ $n->author}}">
<button type="submit" class="btn btn-secondary">Update</button>
</form>
#endforeach
try separating the update into two statements like so
$blog = DB::table('blog')->where('blog_id',$id)->first();
$blog->update([
'blog_title' => $request->title,
'author' => $request->author]);
Also you might want to use models in the future so you can do it like
$blog = Blog::where('blog_id',$id)->first();
Doesn't really shorten your code but it improves the readibility.
Do your update like this:
public function update(Request $request)
{
$post = DB::table('blog')->where('blog_id',$request->blog_id)->first();
$post->blog_title = $request->title;
$post->author = $request->author;
$post->update();
return redirect('/blog');
}

POST method not supported for route in Laravel 6

I am building a discussion form in Laravel 6. The route I used is a POST method and I checked it in route:list. I get the following error, why?
The POST method is not supported for this route. Supported methods:
GET, HEAD, PUT, PATCH, DELETE
View
<form action="{{ route('replies.store', $discussion->slug) }}" method="post">
#csrf
<input type="hidden" name="contents" id="contents">
<trix-editor input="contents"></trix-editor>
<button type="submit" class="btn btn-success btn-sm my-2">
Add Reply
</button>
</form>
Route
Route::resource('discussions/{discussion}/replies', 'RepliesController');
Controller
public function store(CreateReplyRequest $request, Discussion $discussion)
{
auth()->user()->replies()->create([
'contents' => $request->contents,
'discussion_id' => $discussion->id
]);
session()->flash('success', 'Reply Added.');
return redirect()->back();
}
You passed a disccussion object as parameter in order to store user_id within an array.
I think this is not a good practice to store data.
You might notice that your routes/web.php and your html action are fine and use post but you received:
"POST method not supported for route in Laravel 6". This is runtime error. This probably happens when your logic does not make sense for the compiler.
The steps below might help you to accomplish what you want:
1. Eloquent Model(App\Discussion)
protected $fillable = ['contents'];
public function user(){
return $this->belongsTo('App\User');
}
2. Eloquent Model(App\User)
public function discussions(){
return $this->hasMany('App\Discussion');
}
3. Controller
use App\Discussion;
public function store(Request $request){
//validate data
$this->validate($request, [
'contents' => 'required'
]);
//get mass assignable data from the request
$discussion = $request->all();
//store discussion data using discussion object.
Discussion::create($discussion);
session()->flash('success', 'Reply Added.');
return redirect()->back();
}
4. Route(routes/web.php)
Route::post('/replies/store', 'RepliesController#store')->name('replies.store');
5. View
<form action="{{ route('replies.store') }}" method="post">
#csrf
<input type="hidden" name="contents" id="contents">
<trix-editor input="contents"></trix-editor>
<button type="submit" class="btn btn-success btn-sm my-2">
Add Reply
</button>
</form>

Call to a member function getClientOriginalName() on null when upload image use file system Laravel

I want to upload an image using Laravel storage file system in my admin data. However, there's an error when I attempt to upload an image.
Call to a member function getClientOriginalName() on null
Controller
public function store(Request $request)
{
$admin = $request->all();
$fileName = $request->file('foto')->getClientOriginalName();
$destinationPath = 'images/';
$proses = $request->file('foto')->move($destinationPath, $fileName);
if($request->hasFile('foto'))
{
$obj = array (
'foto' => $fileName,
'nama_admin' => $admin['nama_admin'],
'email' => $admin['email'],
'jabatan' => $admin['jabatan'],
'password' => $admin['password'],
'confirm_password' => $admin['confirm_password']
);
DB::table('admins')->insert($obj);
}
return redirect()->route('admin-index');
}
View
<div class="form-group">
<label for="" class="col-md-4">Upload Foto</label>
<div class="col-md-6">
<input type="file" name="foto">
</div>
</div>
Error
You can check wheather you are getting file or not by var_dump($request->file('foto')->getClientOriginalName());
And make sure your form has enctype="multipart/form-data" set
<form enctype="multipart/form-data" method="post" action="{{ url('/store')}}">
<div class="form-group">
<label for="" class="col-md-4">Upload Foto</label>
<div class="col-md-6">
<input type="file" name="foto">
</div>
</div>
</form>
Error because of client Side
<form enctype="multipart/form-data" method="post" action="{{ url('/store')}}">
<div class="form-group">
<label for="" class="col-md-4">Upload Foto</label>
<div class="col-md-6">
<input type="file" name="foto">
</div>
</div>
</form>
you ned to add enctype="multipart/form-data" inside the form
If You are using the form builder version
{!! Form::open(['url' => ['store'],'autocomplete' => 'off','files' => 'true','enctype'=>'multipart/form-data' ]) !!}
{!! Form::close() !!}
Then In your Controller You can check if the request has the file
I have Created the simple handy function to upload the file
Open Your Controller And Paste the code below
private function uploadFile($fileName = '', $destinationPath = '')
{
$fileOriginalName = $fileName->getClientOriginalName();
$timeStringFile = md5(time() . mt_rand(1, 10)) . $fileOriginalName;
$fileName->move($destinationPath, $timeStringFile);
return $timeStringFile;
}
And the store method
Eloquent way
public function store(Request $request)
{
$destinationPath = public_path().'images/';
$fotoFile='';
if ($request->hasFile('foto'))
{
$fotoFile= $this->uploadFile($request->foto,$destinationPath );
}
Admin::create(array_merge($request->all() , ['foto' => $fotoFile]));
return redirect()->route('admin-index')->with('success','Admin Created Successfully');
}
DB Facade Version
if You are using DB use use Illuminate\Support\Facades\DB; in top of your Controller
public function store(Request $request)
{
$admin = $request->all();
$destinationPath = public_path().'images/';
$fotoFile='';
if ($request->hasFile('foto'))
{
$fotoFile = $this->uploadFile($request->foto,$destinationPath );
}
$obj = array (
'foto' => $fotoFile,
'nama_admin' => $admin['nama_admin'],
'email' => $admin['email'],
'jabatan' => $admin['jabatan'],
'password' => $admin['password'],
'confirm_password' => $admin['confirm_password']
);
DB::table('admins')->insert($obj);
return redirect()->route('admin-index');
}
Hope it is clear

Resources