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
Related
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.
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();
So im trying to check if an authenticated user is already following the user, however im getting this error.
Trying to get property of non-object
if ($followers->user_id == auth()->id()){
return true;
}
8 "Trying to get property of non-object"
"/Applications/MAMP/htdocs/elipost/app/MyFollow.php" 34
I'm not sure if im using this method below properly.
$query->where('user_id', auth()->user()->id);
UserController.php
public function getProfile($user)
{
$users = User::with(['posts.likes' => function($query) {
$query->whereNull('deleted_at');
$query->where('user_id', auth()->user()->id);
}, 'follow','follow.follower'])
->with(['followers' => function($query) {
$query->with('follow.followedByMe');
$query->where('user_id', auth()->user()->id);
}])->where('name','=', $user)->get();
$user = $users->map(function(User $myuser){
$myuser['followedByMe'] = $myuser->followers->count() == 0 ? false : true;
// $myuser['followedByMe'] = $myuser->followers->count() == 0 ? false : true;
dd($owl = $myuser['followedByMe']);
return $myuser;
});
User.php
public function follow()
{
return $this->hasMany('App\MyFollow');
}
MyFollow(model)
<?php
namespace App;
use App\User;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Overtrue\LaravelFollow\Traits\CanFollow;
use Overtrue\LaravelFollow\Traits\CanBeFollowed;
class MyFollow extends Model
{
use SoftDeletes, CanFollow, CanBeFollowed;
protected $fillable = [
'user_id',
'followable_id'
];
public $timestamps = false;
protected $table = 'followables';
public function follower()
{
return $this->belongsTo('App\User', 'followable_id');
}
public function followedByMe()
{
foreach($this->follower as $followers) {
if ($followers->user_id == auth()->id()){
return true;
}
}
return false;
}
}
followedByMe is incorrectly looping a single record. Try the following changes:
public function followedByMe()
{
return $this->follower->getKey() === auth()->id();
}
Since follower is a belongsTo relationship, it will only return at most one record, not a collection.
The map function is also incorrectly using array access on a model. You cannot use ['followedByMe'] on an object, to access a property you need to use -> notation as in $myuser->followedByMe. The following shows how to use the map function:
$user = $users->map(function(User $myuser){
return ['followedByMe' => $myuser->followers->count() == 0];
});
Which would return an array similar to:
[
['followedByMe' => true],
['followedByMe' => false],
['followedByMe' => true],
]
I'm a bit new to laravel and try to do a simple thing, just trying to select multiple rows with eloquent and tried :
<?php
namespace App\Http\Controllers;
use Auth;
use App\Company;
use App\User;
use Illuminate\Support\Facades\View;
use Model;
class BaseController extends Controller {
public function __construct() {
//$companies = Company::find(1);
//$companies = Company::all();
$companies = Company::where('owner_id', Auth::user()->id);
print_r($cpm);
View::share ( 'companies', '$companies' );
}
}
But always get this error :
ErrorException
Trying to get property of non-object in BaseController.php (line 16)
And 2 commented lines above are working fine, so i'm a bit lost?
Thanks,
Nicolas
public function __construct() {
//$companies = Company::find(1);
//$companies = Company::all();
$companies = Company::where('owner_id', Auth::user()->id);
print_r($cpm);
View::share ( 'companies', '$companies' );
}
This piece:
$companies = Company::where('owner_id', Auth::user()->id);
Needs to change into this:
$companies = Company::where('owner_id', Auth::user()->id)->get();
The get makes sure your sql gets runned, and the output us returned to $companies.
And I believe
View::share ( 'companies', '$companies' );
needs to be:
View::share ( 'companies', $companies );
resulting in:
public function __construct() {
//$companies = Company::find(1);
//$companies = Company::all();
$companies = Company::where('owner_id', Auth::user()->id)->get();
print_r($cpm);
View::share ( 'companies', $companies );
}
You are trying to get the ID of a loggedin user when no user is logged in. So you should check if a user is logged.
I advice you to use a middleware.
You can also check if the user is logged in using:
if (Auth::check()) {
$companies = Company::where('owner_id', Auth::user()->id)->get();
}
Read this for more information about Authentication: https://laravel.com/docs/5.6/authentication
The where() method returns a Builder object and not the result of the query. You need to call get() method in order to get an exploitable Collection.
I am trying to get lists from mailchimp based on apikey which is stored in database against user_id. I am getting all the lists based in apikey which is stored in my config file in laravel. But here i want to get lists from mailchimp based on api key stored in database.
The code I am using to get all the lists based on apikey from config file is:
public function getLists(Request $request)
{
$request->user()->id;
$result = MailchimpFacade::request( 'lists', ['fields' => 'lists.id,lists.name'] );
$resultArray = ['status' => 1, 'message' => 'Lists appear successfully!', 'dataArray' => $result];
return \Illuminate\Support\Facades\Response::json($resultArray, 200);
}
Here i want to get lists from mailchimp based on apikey stored in database.
You time and help will be highly appreciated!
public function getLists (Request $request)
{
$request->user()->id;
$mc = new MailChimp($request->input('api_key'));
$result = $mc->get('/ping');
return \Illuminate\Support\Facades\Response::json($result, 200);
}
<?php
namespace App\Http\Controllers;
use App\APIKEY;
use DrewM\MailChimp\MailChimp;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Response;
use Illuminate\Support\Facades\Validator;
class ApiController extends Controller
{
public function getLists (Request $request)
{
$request->user()->id;
$mc = new MailChimp($request->input('api_key'));
$result = $mc->get('/ping');
return \Illuminate\Support\Facades\Response::json($result, 200);
}
}
public function getLists(Request $request)
{
Auth::user()->id;
$apikey = $request->input('api_key');
DB::table('apikey')
->where('api_key','=', $apikey)
->get();
if($apikey){
$mc = new MailChimp($apikey);
$mailchimp_ping = $mc->get('lists',['fields' => 'lists.id,lists.name'] );
return \Illuminate\Support\Facades\Response::json($mailchimp_ping, 200);
}
else
{ $errorResponse = [
'message' => 'Lists not found!',
'error' => '401'
];
return Response::json( $errorResponse);
}
}
Use DrewM\MailChimp\MailChimp instead of Facade.
use DrewM\MailChimp\MailChimp;
$mc = new MailChimp($apikey);
$result = $mc->get('lists');
print_r($result);
Full Controller, Edit it according to your need-
<?php
namespace App\Http\Controllers;
use DrewM\MailChimp\MailChimp;
class ApiController extends Controller
{
public function authenticateApiKey()
{
$mc = new MailChimp('48cda414960152d55f97a8f44e28ea20-us17');
$mailchimp_ping = $mc->get('lists');
return \Illuminate\Support\Facades\Response::json($mailchimp_ping, 200);
}
}
See this for further details.