Laravel, return view with Request::old - validation

fHello, for example, i have simple input field (page index.php)
<input type="text" name="name" value="{{Request::old('name')}}">
In controller
$this->validate($request, ['name' => 'required']);
After this, i want make some check without Laravels rules. For example
if($request['name'] != 'Adam') { return view('index.php'); }
But after redirect, Request::old is empty. How to redirect to index.php and save old inputs and use Request::old, or its impossible? Thank you.
PS its example, i know that Laravel has special rules for check inputs value

Old question, but for future reference, you can return the input to a view by flashing the request input just beforehand.
i.e.
session()->flashInput($request->input());
return view('index.php');
then in your view you can use the helper
{{ old('name') }}
or
{{Request::old('name')}}

In Laravel 8.x, you can simply use $request->flash();
Docs: https://laravel.com/docs/8.x/requests#flashing-input-to-the-session

You can use back() instead if any url. These function helps you in any case to be able to return to previous page without writing route.
return back()->withInput();

To add the input to your request try adding:
return view('index.php')->withInput();

Related

Check for blade.php in Laravel

Hello and do not be tired
Is there a way to check for a blade.php file in Laravel?
Because I want to check if the file exists before addressing
You can try something like this
if(view()->exists($view)){
return view($view)->render();
}
return "404 page not found";
Here how you can get know that file exists or not in Laravel
if (\View::exists('some.view')) {
}
reference from this link
https://webdevetc.com/programming-tricks/laravel/laravel-blade/how-to-check-if-a-blade-view-file-exists/
Actually, you don't need this check because it is not a dynamic element. But if there is a reason you need to do it, you can simply use php's own function file_exists("bla.blade.php");. it will return true or false.
To complete the answer of #kamran-khalid you can also include a partial in blade only when the view exists
{{-- include `view.name` only if it exists --}}
#includeIf('view.name', ['status' => 'complete'])
{{-- include the first partial that exists --}}
#includeFirst(['custom.admin', 'admin'], ['status' => 'complete'])
More information in the documentation: https://laravel.com/docs/8.x/blade#including-subviews

Laravel Livewire how to redirect before render

I want to redirect if Auth::user()->id is not equal to Ad->user_id
it does not work inside the mount or hydrate method.
$this->ad = Ad::where('id', $this->ad_id);
if ($this->ad->user_id != Auth::User()->id) {
return redirect()->route('dashboard');
}
You can redirect from mount() method. You can't redirect inside render as you would need to call return redirect('/') which would throw an error "render" method on [App\Http\Livewire\...] must return instance of [Illuminate\View\View]
function mount(){
if(condition fails){
return redirect()->to('someplace');
}
}
Livewire does not do backend redirects as far as I experienced, but rather uses JS to do them. So if you use the $this->redirect method, it will tell rendered component to perform the redirect. Some solutions I've seen on the web were in the render function, if you have an issue that results in a redirect being required, create an empty blade file with a simple div inside, and everywhere you need to redirect the user, set the render view as the blank one, and the FE will take the redirect. A pretty messy fix, but I did not see any better ones currently.
I tried everything but below-mentioned trick worked for me.
Rather than routing from the livewire component we can route from the livewire blade component by adding below code.
#php
$carts = \Cart::getContent();
if(count($carts) == 0)
{
$this->redirect('/shopping-cart/bag');
}
#endphp
Suggestions:
Don't use "return" while redirecting otherwise you might face some Front-end issues.
Don't use "route" while redirecting otherwise the code won't work.

Get Input Data Value in Controller in Laravel

I want to get the value of this input.
<input type="text" name="txtEmployeeNo" value='{{ $employee->employee_no }}'>
Its value is 53210. How can I get that in my controller?
I currently have this on my controller.
$employeeNum = $request->input('txtEmployeeNo');
$employeeSched = Schedule::where(['employee_no'=>$employeeNum])->get();
return view('admin.employeemaintenance.createSchedule',compact(,'employeeSched'));
The problem is when I open and see if it is fetched nothing is showing. I cannot get the input.
Try this, It should must work.
$employeeNum = (isset($request['txtEmployeeNo'])) ? $request['txtEmployeeNo'] : 0;
$employeeSched = Schedule::where(['employee_no'=>$employeeNum])->get();
return view('admin.employeemaintenance.createSchedule',$employeeSched);
In your controller insert this line after opening your function:
dd($request->all);
It will show you everything that has been posted through your form with values. If you get your 'txtEmployeeNo' without value, it means something went wrong when you insterted it in your input.
Check with dev tools if that specific input has any value.
If your input has the value you mentioned and your $request->all() still shows an empty value for your "txtEmployeeNo", then the error is in the HTML/Blade file.
Make sure you create the form correctly
Make sure your input's name equals with the request you are trying to receive in your controller.
If you get null as the value of the $request, that could mean, in your Blade file, the input also has it's value as null.
Try to manually insert a value like <input type="text" name="txtEmployeeNo" value="2"> and see if you get that in your controller. If you do, then the query in your input is wrong.
That's all I could think of without provided Blade and Controller code.
Try this:
$employeeNum = $request->input('txtEmployeeNo');
$employeeSched = Schedule::where('employee_no', $employeeNum)->get();
return view('admin.employeemaintenance.createSchedule',compact('employeeSched'));
well, here is an edit to this answer with the steps needed:
in your routes:
Route::post('yourRouteName','yourController#nameOfFunctionInController')->name('TheNameOfTheRoute');
In your controller:
public function nameOfFunction(Request $request) {
$employeeNum = $request->input('txtEmployeeNo');
$employeeSched = Schedule::where('employee_no', $employeeNum)->get();
return view('admin.employeemaintenance.createSchedule',compact('employeeSched'));
}
And that's it basically.

Get current page name from url using laravel blade

I want to get current page name from url using laravel blade, as I want to use it for dynamic manipulation and put it inside hidden value.
If the URL is admin/coding/colors, I want to get only colors page name.
Is that possible?
If you want it to respond to any uri, irrespective of how many segments are in the url, try:
{{substr(strrchr(url()->current(),"/"),1)}}
This will always get the last segment of the request
Of course, try this:
use \Illuminate\Support\Facades\Request;
{{Request::segment(3)}}
{str_after(url()->current(), 'http://admin/coding/')}}
You should obtain the value in the controller and give it as a variable to your view.
You can do that with the segments method of the Request.
$request->segments()[count($request->segments()) -1]
Your controller should look something like this:
public function someFunctionName(Request $request)
{
$last_url_segment = $request->segments()[count($request->segments()) -1];
return view('view.name', ['last_url_segment', $last_url_segment]);
}
Then, in your view, you can use the variable.
<input type="hidden" name="url" value="{{ $last_url_segment }}">

Laravel Pagination links not including other GET parameters

I am using Eloquent together with Laravel 4's Pagination class.
Problem: When there are some GET parameters in the URL, eg: http://site.example/users?gender=female&body=hot, the pagination links produced only contain the page parameter and nothing else.
Blade Template
{{ $users->link() }}
There's a ->append() function for this, but when we don't know how many of the GET parameters are there, how can we use append() to include the other GET parameters in the paginated links without a whole chunk of if code messing up our blade template?
I think you should use this code in Laravel version 5+.
Also this will work not only with parameter page but also with any other parameter(s):
$users->appends(request()->input())->links();
Personally, I try to avoid using Facades as much as I can. Using global helper functions is less code and much elegant.
UPDATE:
Do not use Input Facade as it is deprecated in Laravel v6+
EDIT: Connor's comment with Mehdi's answer are required to make this work. Thanks to both for their clarifications.
->appends() can accept an array as a parameter, you could pass Input::except('page'), that should do the trick.
Example:
return view('manage/users', [
'users' => $users->appends(Input::except('page'))
]);
You could use
->appends(request()->query())
Example in the Controller:
$users = User::search()->order()->with('type:id,name')
->paginate(30)
->appends(request()->query());
return view('users.index', compact('users'));
Example in the View:
{{ $users->appends(request()->query())->links() }}
Be aware of the Input::all() , it will Include the previous ?page= values again and again in each page you open !
for example if you are in ?page=1 and you open the next page, it will open ?page=1&page=2 So the last value page takes will be the page you see ! not the page you want to see
Solution : use Input::except(array('page'))
Laravel 7.x and above has added new method to paginator:
->withQueryString()
So you can use it like:
{{ $users->withQueryString()->links() }}
For laravel below 7.x use:
{{ $users->appends(request()->query())->links() }}
Not append() but appends()
So, right answer is:
{!! $records->appends(Input::except('page'))->links() !!}
LARAVEL 5
The view must contain something like:
{!! $myItems->appends(Input::except('page'))->render() !!}
Use this construction, to keep all input params but page
{!! $myItems->appends(Request::capture()->except('page'))->render() !!}
Why?
1) you strip down everything that added to request like that
$request->request->add(['variable' => 123]);
2) you don't need $request as input parameter for the function
3) you are excluding "page"
PS) and it works for Laravel 5.1
In Your controller after pagination add withQueryString() like below
$post = Post::paginate(10)->withQueryString();
Include This In Your View
Page
$users->appends(Input::except('page'))
for who one in laravel 5 or greater
in blade:
{{ $table->appends(['id' => $something ])->links() }}
you can get the passed item with
$passed_item=$request->id;
test it with
dd($passed_item);
you must get $something value
In Laravel 7.x you can use it like this:
{{ $results->withQueryString()->links() }}
Pass the page number for pagination as well. Some thing like this
$currentPg = Input::get('page') ? Input::get('page') : '1';
$boards = Cache::remember('boards' . $currentPg, 60, function() {
return WhatEverModel::paginate(15);
});
Many solution here mention using Input...
Input has been removed in Laravel 6, 7, 8
Use Request instead.
Here's the blade statement that worked in my Laravel 8 project:
{{$data->appends(Request::except('page'))->links()}}
Where $data is the PHP object containing the paginated data.
Thanks to Alexandre Danault who pointed this out in this comment.

Resources