Hammad Ahmed Hammad Ahmed - 4 months ago 37
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
and the
field exists in the
table which has a OneToOne relationship with
. 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) {
->where('username', $username);

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.


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) {
        ->where('username', $username);

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

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