Hammad Ahmed Hammad Ahmed - 1 month ago 17
MySQL Question

Laravel Querying Relationship models

I'm trying to build something like twitter. When a user posts a message, the links, mentions and hashtags are linked to the specific user. I'm using this piece of code:

$post = preg_replace('/[@]+([A-Za-z0-9-_]+)/', '<a href="/$1" target="_blank">$0</a>', $post );


Say, for instance, if I posted "Happy New Year @josh #HappyNewYear #2015". Then the link for link in the post would be
<a href = "/josh">@josh</a>
.
But I've this route:

Route::get('/profile{id}', 'UserController@getProfile');


How can I change the link in the post by finding out the user which has the username. I've two table
users
and
user_profile
and the
username
field exists in the
user_profile
table which has a OneToOne relationship with
users
. I'm using the Sentry 2 package.

I've another choice. I can change the route to serve the username for profiles but again I've to find the user which has the username.

When I run this:

public function getProfile($username) {

$user = User::whereIn('username', function($query) {
$query->select('username')
->from('user_profile')
->where('username', $username);
})->get();
}


I get this bug: Undefined variable $username, it has not been declared.
While I'm getting it in the url.

Trying to get answers to both the questions. Thanks for help.

Answer

You get the error because of the variable scope. To use a variable inside a closure you have to inject it with use :

$user = User::whereIn('username', function($query) use ($username) {
    $query->select('username')
        ->from('user_profile')
        ->where('username', $username);
})->get();

However if you have a relation you can simply do this:

$user = User::whereHas('profile', function($q) use ($username){
    $q->where('username', $username);
})->first();