Check for blade.php in Laravel - 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

Related

Laravel: how to create a rendered view from a string instead of a blade file?

I've some html with {{ soimething }} placeholders in a table.
I would like to get the rendered view from this custom html.
I would like to avoid to manually do string replace.
Is it possible?
Note : I seen suggested questions but I ended finding a more concise way to reach my goal. So I post an answer to this question. Please keep this open.
You can use Blade Facade.
use Illuminate\Support\Facades\Blade;
use Illuminate\Support\Facades\Blade;
public function __invoke()
{
$name='Peter Pan';
return Blade::render("
<h1> Hello {$name} </h1>
",['name'=>$name]);
}
Found
We can use \Illuminate\View\Compilers\BladeCompiler::render($string, $data)
Where
$string is the text to parse, for example
Hi {{$username}}
$data is the same associate array we could normally pass down to view() helper, for example [ 'username' => $this->email ]
I was missing this from the official doc: https://laravel.com/docs/9.x/blade#rendering-inline-blade-templates
So we can also use
use Illuminate\Support\Facades\Blade;
Blade::render($string, $data)

Laravel, return view with Request::old

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();

Laravel Blade: Use commands from string

I have variable in Controller:
$abc = '#include('partials.formerror', array(.....))';
And I send that variable to view:
\View::share([
"abc" => $abc,
]);
And I want in view:
......
......
#include('partials.formerror', array(....)
......
......
#include('partials.formerror', array(....) is dynamic content from Controller. But it's COMMAND of Blade, not plain text. How can I do that?
You need a string blade compiler like this one:
https://packagist.org/packages/wpb/string-blade-compiler
Laravel doens't allow blade rendering from strings out of the box.
Fyi: you could also use Blade::compileString which imho is not an elegant solution
your answer is here: https://laravel.com/docs/5.2/views#view-composers
You can create a view composer and attache dynamic content to your view.

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.

Laravel 4: if statement in blade layout works strange

Could someone explain me why I get blank screen with printed string "#extends('layouts.default')" if I request page normally (not ajax)?
#if(!Request::ajax())
#extends('layouts.default')
#section('content')
#endif
Test
#if(!Request::ajax())
#stop
#endif
I'm trying to solve problem with Ajax, I don't want to create 2 templates for each request type and also I do want to use blade templates, so using controller layouts doesn't work for me. How can I do it in blade template? I was looking at this Laravel: how to render only one section of a template?
By the way. If I request it with ajax it works like it should.
Yes #extends has to be on line 1.
And I found solution for PJAX. At the beginning I was not sure this could solve my problem but it did. Don't know why I was afraid to lose blade functionality if you actually can't lose it this way. If someone is using PJAX and needs to use one template with and without layout this could be your solution:
protected $layout = 'layouts.default';
public function index()
{
if(Request::header('X-PJAX'))
{
return $view = View::make('home.index')
->with('title', 'index');
}
else
{
$this->layout->title = 'index';
$this->layout->content = View::make('home.index');
}
}
Try moving #extends to line 1 and you will see the blade template will render properly.
As for solving the ajax problem, I think it's better if you move the logic back to your controller.
Example:
…
if ( Request::ajax() )
{
return Response::eloquent($books);
} else {
return View::make('book.index')->with('books', $books);
}
…
Take a look at this thread for more info: http://forums.laravel.io/viewtopic.php?id=2508
You can still run your condition short handed in the fist line like so
#extends((Request::ajax())?"layout1":"layout2")

Resources