Laravel中添加Facebook个人资料链接及修正LinkedIn链接路径
Hey there! Let's tackle your two Laravel questions one by one, starting with the LinkedIn link issue since that's the immediate problem you're facing.
The root cause here is that the linkedin value stored in your database doesn't include a full HTTP/HTTPS prefix (like https://www.linkedin.com/). Blade is treating it as a relative path, so it's appending it to your website's base domain (https://testb2b.large-it.com/).
Here are two solid solutions:
Option 1: Fix the Data at the Source (Recommended)
Ensure whenever you save a LinkedIn profile link to the personals table, it's a complete URL (e.g., https://www.linkedin.com/sahin instead of linkedin.com/sahin). With this, your original Blade code will work perfectly without any changes.
Option 2: Dynamically Add the Prefix in Blade
If you already have existing data stored without the full prefix, use Laravel's string helper functions to auto-add the correct URL structure. Modify your Blade code like this:
<a href="{{ \Illuminate\Support\Str::start($item->linkedin, 'https://www.linkedin.com/') }}"> <img src="img/linkedin.png" height="30px" width="30px" class="p-1" alt="LinkedIn Profile"> </a>
For even more flexibility (handling cases where some links might already have the prefix), use a quick conditional check:
@php $linkedinUrl = $item->linkedin; if (!\Illuminate\Support\Str::startsWith($linkedinUrl, ['http://', 'https://'])) { $linkedinUrl = 'https://www.linkedin.com/' . ltrim($linkedinUrl, '/'); } @endphp <a href="{{ $linkedinUrl }}"> <img src="img/linkedin.png" height="30px" width="30px" class="p-1" alt="LinkedIn Profile"> </a>
Adding a Facebook link follows a similar pattern to LinkedIn. Here's how to do it step by step:
Add a Facebook Column to Your Database
First, create a migration to add afacebookfield to thepersonalstable:php artisan make:migration add_facebook_to_personals_table --table=personalsOpen the generated migration file and update the
up()method:public function up() { Schema::table('personals', function (Blueprint $table) { $table->string('facebook')->nullable(); // Mark as nullable if some entries won't have a Facebook link }); }Run the migration to apply the change:
php artisan migrateNo Controller Changes Needed
Your current controller uses->get()to fetch all fields from the joined tables, so the newfacebookfield will automatically be included in the$data2collection.Add the Facebook Link to Blade
Use the same URL prefix logic as LinkedIn to ensure correct formatting:<a href="{{ \Illuminate\Support\Str::start($item->facebook, 'https://www.facebook.com/') }}"> <img src="img/facebook.png" height="30px" width="30px" class="p-1" alt="Facebook Profile"> </a>
内容的提问来源于stack exchange,提问作者Russel Monzur

