I have added in my public folder one folder called js and inside a script.js. In the view:
<script type="text/javascript" src="{!! asset('/js/script.js') !!}"></script>
and all is working in local but on the server I receive a get error:
https://url/js/script.js
How is it possible?
you should use {{ }} instead of {!! !!}
<script type="text/javascript" src="{{ asset('js/script.js') }}"></script>
{!! !!} used for Displaying Unescaped Data
By default, Blade {{ }} statements are automatically sent through
PHP's htmlspecialchars function to prevent XSS attacks. If you do not
want your data to be escaped, you may use the following syntax:
1st Simple Way To give the path: As Per Laravel 5.4 File Structure asset folder inside the resources folder So Suppose Your file inside that. ( resources/asset/ ) So You Can Use Like Below Example:
<script type="text/javascript" src="{{ URL::asset('js/jquery.js') }}"></script>
<link rel="stylesheet" href="{{ URL::asset('css/somestylesheet.css') }}" />
2nd Way You can just pass the path to the style sheet .
{!! HTML::style('css/style.css') !!}
You can just pass the path to the javascript.
{!! HTML::script('js/script.js'); !!}
Add the following lines in the require section of composer.json file and run composer update "illuminate/html": "5.*"
Register the service provider in config/app.php by adding the following value into the providers array:
'Illuminate\Html\HtmlServiceProvider'
Register facades by adding these two lines in the aliases array:
'Form'=> 'Illuminate\Html\FormFacade',
'HTML'=> 'Illuminate\Html\HtmlFacade'
3rd Way Place your assets in public directory and use the following:
<script type="text/javascript" src="{{ URL::asset('js/jquery.js') }}"></script>
<link rel="stylesheet" href="{{ URL::asset('css/somestylesheet.css') }}" />
OR ( Use URL::to() )
<link rel="stylesheet" type="text/css" href="{{ URL::to('css/style.css') }}">
<script type="text/javascript" src="{{ URL::to('js/jquery.min.js') }}"></script>
and all is working in local but on the server I receive a get error:
By server, are you referring to a remote server (e.g. VPS)? or PHP's built-in web server?
Have you tried running php artisan cache:clear as well?
I think you can try this for solve issue for http and https because your script and css no run in https url:
First you can create SchemalessUrlGenerator file in App\Libraries:
<?php
namespace App\Libraries;
use Illuminate\Http\Request;
use Illuminate\Routing\RouteCollection;
use Illuminate\Routing\UrlGenerator;
use Illuminate\Support\Str;
class SchemalessUrlGenerator extends UrlGenerator
{
public function __construct(RouteCollection $routes, Request $request)
{
parent::__construct($routes, $request);
}
public function to($path, $extra = [], $secure = null)
{
// First we will check if the URL is already a valid URL. If it is we will not
// try to generate a new one but will simply return the URL as is, which is
// convenient since developers do not always have to check if it's valid.
if ($this->isValidUrl($path)) {
return $path;
}
$scheme = $this->getScheme($secure);
$extra = $this->formatParameters($extra);
$tail = implode('/', array_map(
'rawurlencode', (array) $extra)
);
// Once we have the scheme we will compile the "tail" by collapsing the values
// into a single string delimited by slashes. This just makes it convenient
// for passing the array of parameters to this URL as a list of segments.
$root = $this->getRootUrl($scheme);
if (($queryPosition = strpos($path, '?')) !== false) {
$query = mb_substr($path, $queryPosition);
$path = mb_substr($path, 0, $queryPosition);
} else {
$query = '';
}
return '//' . $this->trimUrl($root, $path, $tail).$query;
}
/**
* {#inheritdoc}
*/
protected function getScheme($secure)
{
// Don't be smart Laravel... ask the browser?!?!
// negotiate the schema to be the same as how page was served
return '//';
}
}
Then you can add SchemalessUrlGenerator related code in App\Providers\AppServiceProvider in register method
$routes = $this->app['router']->getRoutes();
// // Replace UrlGenerator with SchemalessUrlGenerator that will serve content using "//" instead
// // of "http" or "https"
$schemalessUrlGenerator = new SchemalessUrlGenerator($routes, $this->app->make('request'));
$this->app->instance('url', $schemalessUrlGenerator);
Hope this help for you!
Related
This is a complete new application using Laravel 9 and Livewire
By default you have two layouts, guest and app. I want to create a new layout for all my admin things.
So, first I create a component
php artisan make:component AdminLayout
This creates \app\View\Components\AdminLayout.php, it read as:
<?php
namespace App\View\Components;
use Illuminate\View\Component;
class AdminLayout extends Component {
public function render() { return view('layouts.admin'); }
}
As any of the other two AdminLayout.php or GuestLayout.php
So now I write app\resources\views\layouts\admin.blade.php which is a stantandard HTML with the {{ $slot }} blade directive, something as...
<html>
<head>
...
<title>Admin Page</title>
...
#livewireStyles
#vite([...])
</head>
<body>
<main class="...">
{{ $slot }}
</main>
#livewireScripts
</body>
</html>
Then I create the admin routes... The Index class is in \app\Livewire\Admin\Index.php and it is correctly imported
Route::get('', Index::class)->name('home');
The Index.php reads as
class Index extends Component {
public function render() { return view('livewire.admin.index'); }
}
The \app\resources\views\livewire\admin\index.blade.php reads:
<x-admin-layout>
Hello
</x-admin-layout>
So everything seems to be right... now I have two problems that I can't spot/solve. When I load the http:://server.test/admin it should load this page. 1) It doesn't change the title in the page for Admin Page, 2) It always loads the #livewire('navigation-menu'), and looks like the followin picture:
If I add things above the {{ $slot }} or below, they are rendered. If I add another #livewire('navigation-menu') it is rendered. But I'm not able to take it out, even when I'm not telling to display it.
Any idea?
I just noticed that if I add a comment in the guest layout or the admin layout, it simply ignores it. If I add a comment in the app layout it somehow "propagates" to both the guest and admin layout. Is this the expected behaivour?
In my head section of my form.layout.blade.php I have the following:
<head>
<script src="/js/main.js"></script>
<head>
This is layout file is loaded before all pages are loaded. Is there a way to not load main.js for a specific route?
you can use if statement like this. main.js will not load on this page
#if(!Request::is('subpage/url'))
<script src="/js/main.js"></script>
#endif
The workaround I used for not loading scripts on all sites, is that I put script paths in variables in controllers, something like this:
public function show($id){
$scripts[] = '/js/main.js';
view()->share('scripts', $scripts);
return view('view', $someData);
}
This allows me to use this script only on a page I really need it, like this:
#if(isset($scripts))
#foreach($scripts as $key => $value)
<script src="{{mix($value)}}"></script>
#endforeach
#endif
Hope that this can lead you in right direction.
You can use if statements
#if(!in_array(Route::currentRouteName(), ['route.name', ...]))
<script src="/js/main.js"></script>
#endif
this is my code
route.php
Route::get('test/{id}','testController#test');
testController.php
public function test($id){ return('test'); }
test.blade.php
<!DOCTYPE html>
<html>
<head>
<title>a</title>
</head>
<body>
<img src="myPath/myImage.jpg">
</body>
</html>
The result: the image cant be load
note: when i deleted the 'id' parameter it has worked perfectly
What is the error message you are getting?
You will also probably want to change the return value of testController#test to something along the lines of this so you can actually pass the variable to the view.
return view('test', [
'id' => $id,
])
You may also want to have env('APP_DEBUG',true) turned on to get verbose output
the solution : i have changed the value of the src attribute
<img src="{{URL::to('myPath/myImage.jpg')}}">
You need to use:
href="{{ URL::to('yourfile')}}". Also you should place your images in laravel public folder. If you will create folder img in your public folder then you need to something like this: href="{{ URL::to('img\imgname.png')}}".
I'm still new to Laravel. Anyway, I'm making a small system of viewing and creating articles to be shown in the main site. I wanted to create a page that displays an article from the database, using a parameter from the URL, like this:
http://localhost:8000/read/1
The above, for example, will display the article with 'id' value of 1 in the database.
So it works just fine, but problem is, after I got it to work (which took me some time since I'm a newbie), the whole style just disappears from the page. I tried to rewrite everything but it still didn't work. New pages that I create include the style just fine.
This is my route line:
Route::get('read/{id}', array('as' => 'read', 'uses' => 'NewsController#readArticle'));
NewsController readArticle function:
public function readArticle($id) {
$article = NewsMessage::where('id', $id) -> first();
return View::make('news.read', array('article' => $article));
}
And the file read.blade.php (located in views/news/read.blade.php)
#extends('layouts.main')
#section('content')
{{ $article -> title }}
#stop
So the whole PHP code works fine and I manage to get the title. But for some reason, the whole style disappears and this is what I see:
http://puu.sh/ctO6J/db30fbe102.png
So any idea, what have I dont wrong that caused this? The other pages work just fine with the style included.
Thank you!
The issue is that the path to the image is incorrectly specified.
You can either use the built in asset methods or something like {{ URL::to('/')/imagepathhere/filename.jpg }}
Assuming you have your styles links wrote as:
#extends('layouts.main')
#section('styles')
<link href="css/custom.css" rel="stylesheet" />
<link href="css/styles.css" rel="stylesheet" />
#endsection
#section('content')
{{ $article -> title }}
#endsection
Correct Syntax:
#extends('layouts.main')
#section('styles')
<link href="{{ asset('css/custom.css') }}" rel="stylesheet" />
<link href="{{ asset('css/styles.css') }}" rel="stylesheet" />
#endsection
#section('content')
{{ $article -> title }}
#endsection
And make sure your css folder is located at public folder when calling with asset() helper.
This issues of disappearing the whole page styles is causing by accessing the image or css file or any other resources, and the solution is to use asset() helper function.
NOTE: YOUR ROUTES AND CONTROLLER HAS NO ISSUE, YOU DON'T NEED TO TOUCH EITHER.
I am using a fresh build today of Laravel 4.
I have a dashboardController
class DashboardController extends BaseController {
protected $layout = 'layouts.dashboard';
public function index()
{
$this->layout->content = View::make('dashboard.default');
}
}
I have a simple route
Route::get('/', 'DashboardController#index');
I have a blade layout in views/layouts/dashboard.blade.php
For the sake of saving everyone from all of the actual HTML ill use a mock up.
<html>
<head>
<title></title>
</head>
<body>
#yield('content')
</body>
</html>
I have a default blade file in views/dashboard/ that has the following (edited for simplicity)
#section('content')
<p>This is not rocket science</p>
#stop
For some reason the content gets generated before the layout.
I am using a different approach to set the layouts globally to routes using a custom filter. Put the following filter into the app/filters.php
Route::filter('theme', function($route, $request, $response, $layout='layouts.default')
{
// Redirects have no content and errors should handle their own layout.
if ($response->getStatusCode() > 300) return;
//get original view object
$view = $response->getOriginalContent();
//we will render the view nested to the layout
$content = View::make($layout)->nest('_content',$view->getName(), $view->getData())->render();
$response->setContent($content);
});
and now instead of setting layout property in the controller class, you can group the routes and apply the filter as shown below.
Route::group(array('after' => 'theme:layouts.dashboard'), function()
{
Route::get('/admin', 'DashboardController#getIndex');
Route::get('/admin/dashboard', function(){ return View::make('dashboard.default'); });
});
When creating the views, make sure to use the #section('sectionName') in all the sub views and use #yield('sectionName') in the layout views.
I find it easier to do my layout like this for example. I would create my master blade file like so
<html>
<body>
#yield('content');
</body>
</html
And in the blade files that I want to use the master at the top i would put
#extends('master')
then content like so
#section('content')
// content
#stop
Hope this helps.
When you use controller layouts, i.e. $this->layout->..., then you get access to data as variables, not sections. So to access content in your layout you should use...
<html>
<head>
<title></title>
</head>
<body>
<?php echo $content; ?>
</body>
</html>
And in your partial, you would not use #section or #stop...
<p>This is not rocket science</p>