PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, April 18, 2022

[FIXED] How can I modify my Controller so that the query is limited to the user id?

 April 18, 2022     laravel, php     No comments   

Issue

I have my Controller set up as such:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Booking;

class eventController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $events = array();
        $bookings = Booking::all();
        foreach($bookings as $booking) {
                'id' => $booking->id,
                'title' => $booking->title,
                'resourceId' => $booking->resourceId,
                'start' => $booking->start_date,
                'end' => $booking->end_date,
            ];
        }
        return view('home', ['events' => $events]);
    }
}

Here I can pass everything from my DB into my view, but how can I filter these out such that only entries from a certain user_id is displayed? This is what my table looks like: https://imgur.com/AUZhA1L.

I have attempted to use the {user} blade but am stuck.


Solution

Change this line:

$bookings = Booking::all();

to this:

$bookings = Booking::where('user_id', 9)->get();

Or if you want to get the logged in user, you can use Auth.

Add this line after use App\Models\Booking;

use Illuminate\Support\Facades\Auth;

and then:

$bookings = Booking::where('user_id', Auth::id())->get();


Answered By - Rouhollah Mazarei
Answer Checked By - Mary Flores (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing