laravel blade include files with relative path - laravel

In laravel blade system when we want to include a partial blade file we have to write the full path every time for each file. and when we rename a folder then we will have to check every #include of files inside it. sometimes it would be really easy to include with relative paths. is there any way to do that?
for example we have a blade file in this path :
resources/views/desktop/modules/home/home.blade.php
and I need to include a blade file that is near that file :
#include('desktop.modules.home.slide')
with relative path it would be something like this :
#include('.slide')
is there any way to do this?

if someone still interest with relative path to current view file, put this code in the boot method of AppServiceProvider.php or any provider you wish
Blade::directive('relativeInclude', function ($args) {
$args = Blade::stripParentheses($args);
$viewBasePath = Blade::getPath();
foreach ($this->app['config']['view.paths'] as $path) {
if (substr($viewBasePath,0,strlen($path)) === $path) {
$viewBasePath = substr($viewBasePath,strlen($path));
break;
}
}
$viewBasePath = dirname(trim($viewBasePath,'\/'));
$args = substr_replace($args, $viewBasePath.'.', 1, 0);
return "<?php echo \$__env->make({$args}, \Illuminate\Support\Arr::except(get_defined_vars(), ['__data', '__path']))->render(); ?>";
});
and then use
#relativeInclude('partials.content', $data)
to include the content.blade.php from the sibling directory called partials
good luck for everyone

you need to create custom blade directive for that, the native include directive doesn't work like that.
read this page to learn how to create custom blade directive :
https://scotch.io/tutorials/all-about-writing-custom-blade-directives
\Blade::directive('include2', function ($path_relative) {
$view_file_root = ''; // you need to find this path with help of php functions, try some of them.
$full_path = $view_file_root . path_relative;
return view::make($full_path)->render();
});
then in blade file you can use relative path to include view files :
#include2('.slide')
I tried to tell you the idea. try and test yourself.

There’s now a package doing both relative and absolute includes (lfukumori/laravel-blade-include-relative) working with #include, #includeIf, #includeWhen, #each and #includeFirst directives. I just pulled it in a project, it works well.

A sleek option, in case you want to organise view files in sub-folders:
public function ...(Request $request) {
$blade_path = "folder.subfolder.subsubfolder.";
$data = (object)array(
".." => "..",
".." => $..,
"blade_path" => $blade_path,
);
return view($data->blade_path . 'view_file_name', compact('data'));
}
Then in the view blade (or wherever else you want to include):
#include($blade_path . 'another_view_file_name')

Related

Get image from resources folder - Laravel

Can I get and display an image in view from a resources folder instead of public folder? If yes, how can I do that?
resources folder should not be used to store images
That's not where public, static assets (like images, js, css etc) should be.
Put them inside public/ folder
The resources/assets/ directory is for storing pre-processed assets, so to speak.
For example, if you have 3 different CSS files but want to merge them
into one and render that new single file in the browser (to increase
page load speed). In this scenario, the 3 CSS files will be put
somewhere inside resources/assets/.
These files can then be processed, and the new merged file will go inside public.
Reference:
https://laracasts.com/discuss/channels/laravel/image-assets?page=1
You can make a route specifically for displaying images.
Route::get('/resources/app/uploads/{filename}', function($filename){
$path = resource_path() . '/app/uploads/' . $filename;
if(!File::exists($path)) {
return response()->json(['message' => 'Image not found.'], 404);
}
$file = File::get($path);
$type = File::mimeType($path);
$response = Response::make($file, 200);
$response->header("Content-Type", $type);
return $response;
});
now you can go to localhost/resources/app/uploads/filename.png and it should display the image.reference How to get image from resources in Laravel?
But again say that resources folder should not be used to store images That's not where public, static assets (like images, js, css etc) should be. as #sehdev says his answer..
Anwsear to your question is in Laravel's doc: https://laravel.com/docs/5.7/helpers#method-app-path
$path = base_path('resources/path/to/img_dir');
You can create an symlink:
ln -s /path/to/laravel/resources/images /path/to/laravel/public/images
Although as other users have already pointed out, the resource directory is not intended to be used publicly.
I agree with #sehdev.
However, if you still want to serve your image from resources directory, here is a solution that gets the job done.
In your view:
<img src="/your-image" />
In Route:
Route::get('/your-image', function ()
{
$filepath = '/path/to/your/file';
$file = File::get($filepath);
$type = File::mimeType($filepath);
$response = Response::make($file, 200);
$response->header("Content-Type", $type);
$response->header("Content-Length", File::size($filepath));
return $response;
})
this is not the best solution. I suggest you to move your assets to public directory.
Edit: Use laravel functions. I suggest not to take file path from url because it may subject to Directory Traversal.

How to get translate message in controller Laravel?

I have file excel.php by the path /resources/lang/en/excel.php
Then in controller I tried to fetch word by key:
use Lang;
echo Lang::get('excel.idEvent');
Also I tried:
dd(echo __('excel.idEvent'));
Whats is right way to do that?
First, your excel.php file must be in the right format:
<?php
return [
'welcome' => 'Welcome to our application'
];
The right way to get it on your blade template in fact it is:
echo __('excel.welcome');
or
echo __('Welcome to our application');
The way to do it on your controller is:
use Lang;
Lang::get('excel.welcome');
If you are not using Facades: use \Illuminate\Support\Facades\Lang;
You can also use the trans() function, ex:
Route::get('/', function () {
echo trans('messages.welcome');
});
If you use JSON translation files, you might have to use __().
Here are all the ways to use:
#lang('...') // only in blade files
__('...')
Lang::get('...')
trans('...')
app('translator')->get('...')
Lang::trans('...')
They all defer to \Illuminate\Translation\Translator::get() eventually.

laravel 5.2 carousel only in index page doesn't wok

I use laravel 5.2 and tried to display a carousel only in index page but doesn't work.
I chose that the codes are not "spreaded" on the index page, they are stored in: public/carousel/carousel.php, too(not ...blade.php).
route.php:
Route::get('/', 'HomeController#index')
HomeController.php:
{
$cats = Category::all();
$carousel = public_path('carousel/carousel.php');
//$carousel = storage_path('public/carousel/carousel.php');
return view('layouts.app', compact('cats', 'carousel'));
}
layouts/app.blade.php:
{{-- #include('carousel/carousel');--}}
#if($carousel)
{{ $carousel }}
#endif
#yield('content')
Finally it displays only: C:\wamp\www\app_name\public\carousel/carousel.php.
Can you help me or point to another better way?
In your controller, you are passing to the view a variable called $carousel, which is the path to your file, as you defined here:
$carousel = public_path('carousel/carousel.php');
This is the reason why it only displays the string. You need to get the actual content of the file:
$carousel = file_get_content(public_path('carousel/carousel.php'));
A better and more laravel-ish way to do it would be to rename the file to carousel.blade.php, store it into the resources/views folder and simply include it from your main blade file (without the need of doing anything in the controller):
#include('carousel')
If you need to display the carousel on certain pages only, you can simply pass a variable $carousel = true on the pages that needs to display it:
$carousel = true;
return view('layouts.app',compact('carousel'));
And in your blade view, include the carousel file only when this variables is present and is true:
#includeWhen(isset($carousel) && $carousel, 'carousel')

Remove unused Images/files from upload folder laravel

I have laravel5.4 application.I want to remove unused images/files from my upload folder which is not available in my database.
For example :
I have 50 images in my upload folder for user profile but some of the image not use for any user.i think he removed or update his image from frontend.
Yes i know we need to code to remove file when user update or remove profile picture at a time also delete from upload folder.but my app run from many time and i want to remove unused file using script not manually beacause i have lot's of files so it's hard to check and remove file manually.anyone can you please help me for create any function for remove file from folder.
Sorry for my bad English.
I use something like this in my AdminController to remove images by clicking on a button.
Maybe you need to change the path or extensions
public function deleteUnusedImages()
{
$file_types = [
'gif',
'jpg',
'jpeg',
'png'
];
$directory = public_path();
$files = File::allFiles($directory);
foreach ($files as $file)
{
$ext = strtolower(pathinfo($file, PATHINFO_EXTENSION));
if (in_array($ext, $file_types)) {
if(DB::table('users')->where('votes', '=', $file)->count())
continue; // continue if the picture is in use
echo 'removed' . basename($file)."<br />";
unlink($file); // delete if picture isn't in use
}
}
}

Using Blade directives outside of templates

Laravel 5.1: I defined a few custom directives inside a BladeServiceProvider (example below). Now I would like to use them outside of a view template to format strings (I am writing an EXCEL file with PHPExcel in a custom ExportService class). Is it possible to reuse my directives?
Blade::directive('appFormatDate', function($expression) {
return "<?php
if (!is_null($expression)) {
echo date(\Config::get('custom.dateformat'), strtotime($expression));
}
else {
echo '-';
}
?>";
});
The BladeCompiler has a compileString method, which allows you to use the Blade directives outside the views. :)
So, you can do things like this:
$timestamp = '2015-11-10 17:41:53';
$result = Blade::compileString('#appFormatDate($timestamp)');
You can use this:
use Illuminate\Support\Facades\Blade;
$timestamp = '2023-01-28 12:41:53';
Blade::render("#appFormatDate({$timestamp})");

Resources