Laravel 5.3 - htmlspecialchars() expects parameter 1 to be string

試著忘記壹切 提交于 2019-11-26 18:28:58

问题


I am new to laravel and I am enjoying it. While working on a social media project I got this error: htmlspecialchars() expects parameter 1 to be string, object given (View: C:\wamp64\www\histoirevraie\resources\views\user\profile.blade.php)

I have checked some questions on this site but I have not found a question that solves my problem.

this is what my profile.blade.php is made of:

<ul class="profile-rows">
    <li>
        <span class="the-label">Last visit: </span>
        <span class="the-value mark green">{{ \Carbon\Carbon::createFromFormat('Y-m-d H:i:s', $user->lastVisit)->diffForHumans(\Carbon\Carbon::now())}}</span>
    </li>
    <li>
        <span class="the-label">Member since: </span>
        <span class="the-value mark light-gray">{{ $user->created_at->format('F Y') }}</span>
    </li>
    <li>
        <span class="the-label">Profile views: </span>
        <span class="the-value mark light-gray">5146</span>
    </li>
    <li>
        <span class="the-label">Living In: </span>
        <span class="the-value">{{ $user->town }}</span>
    </li>
    <li>
        <span class="the-label">Website: </span>
        <span class="the-value"><a href="{{ url($user->website) }}">{{ $user->website }}</a></span>
    </li>
</ul>

All the information about the user are given by a controller:

public function index($username){
        $user = User::where('username', $username)->first();
        return view('user.profile', compact('user'));
    }

Kindly help me solve this problem!


回答1:


I think your $user->website is empty/blank.

If you look at the url() helper method, Laravel will return an instance of UrlGenerator if $path is null.

So in your case if $user->website is empty, you'd get UrlGenerator back and thus your error about htmlspecialchars getting an object.

One simple solution would be to wrap your html chunk with a check:

@if($user->website)
    <li>
        ...
    </li>
@endif



回答2:


In my case, i used a function inside blade file like $brand->products() and it was returning array, thats why i was seeing the message.

when i changed my code and returning string, the error was gone.




回答3:


I was getting this because in my view I was using $errors->get('username') to show errors but get() returns an array. Switching to $errors->first('username') fixed this.



来源:https://stackoverflow.com/questions/40045920/laravel-5-3-htmlspecialchars-expects-parameter-1-to-be-string

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!