BigJobbies
BigJobbies

Reputation: 193

If else statement based on database row

Im having a bit of trouble figuring out how to interact with the database in Laravel.

Im writing a small app, and its come to the point where I need to enter, check and return results.

I have followed the docs to setup authentication and now I can have users log in and out.

So what I want to do is store letters.

I have a table called letters.

A user can write as many letters as they want, their user ID is stored in the letters table in the column called userID

When a user clicks on the 'Letters' navigation item, it takes them to the

Route::get('letters')..........

When it loads the view, if there are no letters in the database I want it to say 'No previous letters' .. if there is some letters in the DB, I just want it to say 'Welcome back'

I cant find how or where to achieve this.

I'm hoping someone can help me out and give me a bit of a hand writing the code as I cant find anything in the docs.

Upvotes: 0

Views: 431

Answers (1)

Antoine Augusti
Antoine Augusti

Reputation: 1608

You need to do this in a controller.

Route::get('letters', ['uses' => 'LettersController@index']);

And then in your letters controller

public function index()
{

    // Grab letters for the user. You need to be sure that the user is logged in
    $letters = Letter::forUser(Auth::user())->get();

    $data = [
        'letters' => $letters
    ];

    // You will be able to call $letters->count() in your view
    return View::make('letters.index', $data);
}

In your letter Model

public function scopeForUser(User $u)
{
    return $query->where('user_id', '=', $u->id);
}

Upvotes: 1

Related Questions