I'm trying to request the $year off my form in my show method but it's returning null. I'm logging time entries and I want to query the times by years like this: $times = Time::where('user_id', $id)->whereYear('start_day', $request->year)->get();. This query works inside of my getReports method, but not in my show method which Is where I want it to work. If I dd($request->all()) inside of my show method It just returns an empty array. I'm not sure how to fix this, I believe it has to do with my route getReport. Is there a way to pass those values into the show method? I just need the $request->year to work so I can query properly.
Routes:
Route::resource('admin/reports', 'Admin\ReportController', [ 'as' => 'admin'])->middleware('admin');
Route::post('admin/reports/getReport', 'Admin\ReportController#getReport')->name('admin.getReport')->middleware('admin');
Form POST:
<form method="POST" action="{{ route('admin.getReport') }}">
Controller:
<?php
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Http\Helper\ReportHelper;
use App\Time;
use App\User;
use App\Category;
use App\Offtime;
use Carbon\Carbon;
use Auth;
use Date;
use PDF;
use Session;
class ReportController extends Controller
{
public function create() {
$users = User::all();
$times = Time::all();
$years = array();
$length_times = count($times);
for($i=0;$i<$length_times;$i++){
$year = Carbon::parse($times[$i]->start_day)->format('Y');
array_push($years, $year);
}
$years = array_unique($years);
return view('admin.report.create', compact('users', 'years'));
}
public function show($id, Request $request) {
$user = User::find($id);
if (!$user) {
return false;
}
$times = Time::where('user_id', $id)->get();
return view ('admin.report.show', compact('user','times')
}
public function getReport(Request $request) {
$form_user = $request->form_user;
$year = $request->year;
if (!$form_user) {
return abort(404);
}
$user = User::find($form_user);
if ($user) {
return redirect()->route('admin.reports.show', $user->id);
}
return abort(404);
}
}
For default show uses GET method and you are trying to make a POST.
getReport you defined as post, that's why it's working.
More information about route resource
https://laravel.com/docs/5.7/controllers
In this case, I prefer to use Route Model Binding
public function show(User $user) {
$times = Time::where('user_id', $user->id)->get();
return view ('admin.report.show', compact('user','times')
}
This will handel if the user does not exist.
Related
I have a variable that is $data1, i want to share the value of $data1 with all my controllers and use it
in my >FirstController
$data1 = reservation::select('user_id')
->where('date',request('date'))
->where('time',request('time'))
->where('room_id',request('room_id'))
->get();
in my >SecondController (( where I want to use the value of data1 ))
$msg = new message();
$msg->date = Carbon::now();
$msg->content = request('content');
$msg->user_id = Auth::user()->id;
$msg->reciver = $data1; // here is where i want to use the value of $data1
Note: the value of $data1 changes.
UPDATE:
I have a form (res.blade.php) where the user inserts the data the data I request in the first controller/date, time, room_id /. then I redirect the user to another blade where he inserts new info (content) then I save the new data + the $data1 I got from the first blade's inputs
Create a middleware CommonData.php with below function:
public function handle($request, Closure $next)
{
$data1 = reservation::select('user_id')
->where('date',request('date'))
->where('time',request('time'))
->where('room_id',request('room_id'))
->get();
$request->merge(['data1'=>$data1);
return $next($request);
}
Use this in any controller like this:
$request->data1 or request('data1')
You can generate a global middleware with name like Data1Middleware.php:
public function handle($request, Closure $next)
{
$data1 = reservation::select('user_id')
->where('date',request('date'))
->where('time',request('time'))
->where('room_id',request('room_id'))
->get();
$request->request->add(['data1', $data1]);
return $next($request);
}
and add to $middleware in app/Http/Kernel.php as resource.
protected middleware = [
'Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode',
'Illuminate\Cookie\Middleware\EncryptCookies',
'Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse',
'Illuminate\Session\Middleware\StartSession',
'Illuminate\View\Middleware\ShareErrorsFromSession',
'App\Http\Middleware\VerifyCsrfToken',
//....
\App\Http\Middleware\Data1Middleware::class,
]
EDITED:
if "reservation" is your model, maybe it must be CamelCase (eg: Reservation) and in top of the middleware file add this:
<?php
//....
use App\Models\Reservation;
//....
public function handle($request, Closure $next)
{
$data1 = Reservation::select('user_id')
->where('date',request('date'))
->where('time',request('time'))
->where('room_id',request('room_id'))
->get();
$request->request->add(['data1', $data1]);
return $next($request);
}
but if "reservation" is the database table name, so you can fetch data with query builder:
use Illuminate\Support\Facades\DB;
public function handle($request, Closure $next)
{
$data1 = DB::table('reservation')::select('user_id')
->where('date',request('date'))
->where('time',request('time'))
->where('room_id',request('room_id'))
->get();
$request->request->add(['data1', $data1]);
return $next($request);
}
Let's solve this using a PHP Trait.
Create a Trait
<?PHP
namespace App\Traits;
use App\Models\Reservation;
trait HasReservationData
{
public function reservationData()
{
// Better keep the model name start's with capital letter i.e. Pascal Case
return Reservation::select('user_id')
->where('date',request('date'))
->where('time',request('time'))
->where('room_id',request('room_id'))
->get();
}
}
Now let's use the Trait for our Controllers that need the reservation data.
<?PHP
namespace App\Http\Controllers\StackOverFlow;
use App\Traits\HasReservationData;
class FirstController
{
use HasReservationData;
public function someMethod()
{
// You have the data here and manipulate the data however you want
$data = $this->reservationData();
$msg = new Message();
$msg->date = now();
$msg->content = request('content');
$msg->user_id = Auth::user()->id;
$msg->reciver = $data;
}
}
Maybe another controller
<?PHP
namespace App\Http\Controllers\StackOverFlow;
use App\Traits\HasReservationData;
class SecondController
{
use HasReservationData;
public function someMethod()
{
// You have the data here and manipulate the data however you want
$data = $this->reservationData();
}
}
So, what i`m trying to do here is to save an image to an specific user that is logged in. and it gives me this error
<?php
namespace App\Http\Controllers\Auth;
use Auth;
use Illuminate\Http\Request;
use App\Models\ProfileEmployee;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Validator;
class ImageUploadController extends Controller
{
public function index()
{
$profilasdeimage = ProfilasdeEmployee::where('uid', Auth::user()->id)->first();
return vieasdw('editareemasdployee', compact('profileiasdmage'));
}
public function store(Requasdest $request)
{
$emplasdoyee = ProfileEasdmployee::where('uiasdd', Autasdh::user()->id);
if ($request->hasfile('imasdage')){
$file = $request->file('image');
$exteasdnsion = $file->getClientOriginalExtension();
$fileasdname = md5(time()).'.'.$extension;
$fiasdle->move('public/imaginasdeprofil',$filename);
$empasdloyee->imagasde=$filename;
} else {
return $request;
$emplasdoyee->imasdage='';
}
$emplasdoyee->save(); --->> this is the problem
return view('imageuplasdoad')->with('profasdileimage',$emplasdoyee);
}
}
i want to use this database table to fill the 'image' using the id provided from table users as uid in this table
protected $filasdlable = [
'iasdd', 'uiasdd', 'fasdirst_nasdame', 'lasdast_nasdame','phasdone', 'casdv', 'imasdage', 'addasdress', 'ciasdty',
];
Add first() to your query or use find:
$employee = ProfileEmployee::where('uid', Auth::user()->id)->first();
I put logic from my function index() of UserController in trait taht i created:
public function index()
{
$this->authorize('view', Auth::user());
$users = QueryBuilder::for(User::class)
->allowedIncludes('kids','roles','articles','recordings')
->allowedFilters('first_name', 'last_name', 'email')
->get();
return UserResource::collection($users);
}
and this is my trait :
<?php
namespace App\Http\Traits;
use App\Models\User;
use Spatie\QueryBuilder\QueryBuilder;
trait Filterable
{
public function filter()
{
$users = QueryBuilder::for(User::class)
->allowedIncludes('kids','roles','articles','recordings')
->allowedFilters('first_name', 'last_name', 'email')
->get();
return $users;
}
}
So now my function index() looks like this:
use Filterable;
public function index()
{
$this->authorize('view', Auth::user());
$users = $this->filter();
return UserResource::collection($users);
Now when i do this in my postman
{{url}}/api/users?filter[first_name]=anna
it works and it returns anna from my database but when I try
{{url}}/api/users?include=roles
it return every user from database but does not include roles.
Can somebody help me with this?
This is taken straight from the github page: https://github.com/spatie/laravel-query-builder#custom-filters
Custom filters
use Spatie\QueryBuilder\Filters\Filter;
use Illuminate\Database\Eloquent\Builder;
class FiltersUserPermission implements Filter
{
public function __invoke(Builder $query, $value, string $property) : Builder
{
return $query->whereHas('permissions', function (Builder $query) use ($value) {
$query->where('name', $value);
});
}
}
use Spatie\QueryBuilder\Filter;
// GET /users?filter[permission]=createPosts
$users = QueryBuilder::for(User::class)
->allowedFilters(Filter::custom('permission', FiltersUserPermission::class))
->get();
// $users will contain all users that have the `createPosts` permission
I want to be able to restrict users to only be able to see their own profiles in my laravel project. So when a user wants to access their profile, they would go to the url followed by /userprofile/{id}. But as of right now, any user can type in the specific id of a different user and access their profile. So if I'm logged in as the first user to register, I would have an id of 1. But I only want to be able to access my profile. If I try to type in id 2 or 3 in the url I want it to kick me back to the homepage. Any idea how I could accomplish this? Using some sort of middleware perhaps?
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use DB;
use App\User;
use App\Salutation;
use App\Http\Requests\UserRequest;
use Auth;
class HomeController extends Controller
{
public function index(){
$users_info = User::all();
return view('userprofile.index', compact("users_info"));
}
public function show($user_info){
$user_info = User::find($user_info);
return view('userprofile.show', compact("user_info"));
}
public function create(){
return view('userprofile.create');
}
public function store(UserRequest $request){
$formData = $request->all();
User::create($formData);
return redirect('userprofile');
}
public function edit($user_info) {
$user_info = User::findOrFail($user_info);
return view('userprofile.edit', compact("user_info"));
}
public function update(UserRequest $request, $user_info){
$formData = $request->all();
$user_info = User::findOrFail($user_info);
$user_info->update($formData);
return redirect('userprofile');
}
public function __construct(){
$this->middleware('auth', ['only' =>['create', 'edit',
'destroy']]);
}
}
just compare the current user with param id
example:
public function getProfile(Request $request, $id)
{
if(Auth::id() == $id) {
// valid user
$user_info = Auth::user();
return view('userprofile.show', compact("user_info"));
} else {
//not allowed
}
}
Here is my Controller.
<?php
/**
* Created by PhpStorm.
* User: ed
* Date: 05/02/16
* Time: 09:33
*/
namespace App\Http\Controllers\API\V1;
use App\Certificate;
use App\Country;
use App\Film;
use App\FilmExtra;
use App\FilmFavourite;
use App\FilmGenre;
use App\FilmLike;
use App\FilmView;
use App\Genre;
use App\Language;
use App\Magazine;
use App\News;
use App\User;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Input;
class MagazineController extends ApiController
{
public function viewAll(){
echo Auth::user()->id;
exit;
$user_id = Input::get('user_id');
$magazines = Magazine::paginate(5);
return parent::api_response($magazines->toArray(), true, ['return' => 'all magazines'], 200);
}
public function getMagazine($id){
$magazine = Magazine::find($id);
if($magazine){
return parent::api_response($magazine->toArray(), true, ['return' => 'magazine details'], 200);
}else{
return parent::api_response([], false, ['error' => 'Couldn\'t find that magazine'], 404);
}
}
protected function getURL($id){
$magazine = Magazine::find($id);
if($magazine){
return parent::api_response(['url' => $magazine->file_url], true, ['return' => 'magazine url'], 200);
}else{
return parent::api_response([], false, ['error' => 'Couldn\'t find that magazine'], 404);
}
}
public function search($term){
$magazines = Magazine::search($term)->paginate(5);
return parent::api_response($magazines, true, ['return' => 'search for '.$term], 200);
}
public function purchased(){
$magazines = Magazine::leftJoin('ordered_items', 'ordered_items.item_id', '=', 'magazines.id')
->leftJoin('orders', 'orders.id', '=', 'ordered_items.order_id')
->leftJoin('items', 'items.id', '=', 'ordered_items.item_id')
->where('orders.user_id', $user_id)
->where('items.class', 'book');
if(Input::get('filter')) {
$jsonFilter = Input::get('filter');
$filters = json_decode($jsonFilter);
foreach ($filters as $filter => $value){
switch ($filter){
case "genre":
if($value){
$magazines = $magazines->whereHas('genre', function ($query) use($value) {
$query->whereIn('genre_id', $value);
});
}
break;
case "cert":
if($value){
$magazines = $magazines->whereIn('cert', $value);
}
break;
case "country":
if($value){
$magazines = $magazines->whereIn('country', $value);
}
break;
case "lang":
if($value){
$magazines = $magazines->whereHas('languages', function ($query) use($value) {
$query->whereIn('language_id', $value);
});
}
break;
}
}
}
$magazines = $magazines->paginate(5);
return parent::api_response($magazines->toArray(), true, ['return' => 'all magazines'], 200);
}
}
If i call any of the function for this controller i am not able to get my Auth::user()->id.
it's throwing an error.
ErrorException in MagazineController.php line 54:
Trying to get property of non-object
If i try to echo Auth::user()->id in any other controller, its working fine.
using laravel 5.2
Can anybody help me ?
don't hesitate to ask any question if you want.
Probably the Auth::user returns nulland you are trying to get id of null.
So make sure that user is logged like:
if (Auth::check()) {
// The user is logged in...
echo Auth::user()->id;
}
Ensure your routes for this controller are wrapped in the web middleware group.
Also, since MagazineController extends ApiController, ensure that ApiController extends Controller.
Use it like this the Laravel 5.2 way
$user_collection = Auth::user();
echo $user_collection->id;
exit;
Did you changed the id name of your users table? I experienced that. I made mine all capital (ID). I was on Linux and db, table, and column names are case sensitive. Try checking the id column of your users table.
That is, if you're sure that the user is logged in. Else, it would be null if I'm not mistaken.
Put your controller under a login Middleware to ensure you have a logged in user, or simply put a verification before you access user id:
if (Auth::check()) {
$id = Auth::user()->id;
}
What ApiController do?
Change the namespace at the top to
namespace App\Http\Controllers;
Try to change ApiController with plain Controller and check what will be happen
Instead of:
class MagazineController extends ApiController
Change it like so:
class MagazineController extends Controller