deleting a user with query builder laravel - php

I'm trying to delete a user account using laravel query builder so I'm doing this
AuthRepository
class AuthRepository implements IAuthRepository
{
....
public function delete($user_id)
{
$res = User::where('id', $user_id->id)->delete();;
if ($res) {
return response('Success, user was deleted', 204);
} else {
return response()->json(error);
}
}
}
In controller
class AuthController extends Controller
{
protected $auth;
public function delete($user_id)
{
return $user_id->delete();
}
}
in api.php
Route::group(['prefix' => 'auth'], function () {
Route::group(['middleware' => 'auth:api'], function () {
// Delete user
Route::post('user/delete/{user_id}', 'AuthController#delete');
});
});
Passing user_id to ${API_URL}/auth/user/delete/{user_id} I'm facing
Call to a member function delete() in Controller on line return $user_id->delete();. Can someone please explain me why is this happening, thanks.

Take advantage of the route model binding and to this instead:
public function delete(User $user)
{
return $user->delete();
}
And your route:
Route::post('user/delete/{user}', 'AuthController#delete');
You cannot call delete() on an integer.

If you don't want to use the Route model binding as suggested by #nakov and insist on using id then you have to get the user first before deleting.
public function delete($user_id)
{
$user = User::findOrFail($user_id);
return $user->delete();
}

Related

Laravel Dingo FindOrFail returns empty array

I have a table sites with list of sites with following columns ('id', 'path', 'site_link'). I've written in a Site model public $timestamps = false; so that it won't try to work with time what I don't need.
Also I have the following routes
$api = app('Dingo\Api\Routing\Router');
$api->version('v1', function ($api) {
$api->get('sites', 'App\Http\Controllers\SiteController#index');
$api->get('sites/{site}', 'App\Http\Controllers\SiteController#show');
});
The first one is working fine and returning all the data, however the second one is returning just [].
I have a controller which is below
namespace App\Http\Controllers;
use Illuminate\Http\Request;
Use App\Site;
class SiteController extends Controller
{
public function index()
{
return Site::all();
}
public function show(Site $site)
{
return Site::findOrFail($site);
}
public function store(Request $request)
{
$site = Site::create($request->all());
return response()->json($site, 201);
}
public function update(Request $request, Site $site)
{
$site->update($request->all());
return response()->json($site, 200);
}
public function delete(Site $site)
{
$site->delete();
return response()->json(null, 204);
}
}
The show method in your SiteController is taking a Site object. However the route is set up to only take the siteId. The code below should work for you based on how you've set up your routes.
public function show($site)
{
return Site::findOrFail($site);
}
Apply same to all your other controller methods since you want pass the site id via the url to the controller methods.

Laravel 5.4 User Profile NotFoundHttpException

I am creating a user profile that allows him to modify his information here is the code
class ProfilesController extends Controller
{
public function __construct()
{
$this->middleware('auth');
}
public function index()
{
return view('content.profil');
}
public function editProfile($id)
{
$user = User::find($id);
return view('content.edit', ['user' => $user]);
}
public function updateProfile(Request $request, $id)
{
$user = User::find($id);
$user->name = $request->input('name');
$user->nom = $request->input('nom');
$user->prenom = $request->input('prenom');
$user->adresse = $request->input('adresse');
$user->code_postal = $request->input('code_postal');
$user->ville = $request->input('ville');
$user->pays = $request->input('pays');
$user->num_tele = $request->input('num_tele');
$user->save();
return redirect('/profil');
}
}
Web.php
Route::group(['middleware' =>'auth'], function(){
Route::get('/profil', 'ProfilesController#index')->name('profil');
Route::get('/content', 'ProfilesController#editProfile')->name('profil.edit');
Route::post('/content', 'ProfilesController#updateProfile')->name('profil.update');
});
the view folder tree looks like
view/content/profil.blade.php
view/content/edit.blade.php
the problem is that the routes are defined but it shows me this error message:
(1/1) NotFoundHttpException
I don't know where the problem exists exactly and
thanks in advance
Compared to your routes (web.php) and what you want, this is what your web.php file should be
Route::group(['middleware' =>'auth'], function(){
Route::get('/profil', 'ProfilesController#index')->name('profil');
Route::get('/content/{id}/editProfile', 'ProfilesController#editProfile')->name('profil.edit');
Route::post('/content/{id}', 'ProfilesController#updateProfile')->name('profil.update');
});
Correct your profil.edit route to /content/{id}/editProfile and profil.update in the same way.
And if you have named routes try to use route() helper instead of url() to generate url's, it's cleaner are more universal.

Issue accessing Auth() object data in Laravel class

I am seeing some behaviour. I can't explain when accessing user data via the Auth facade in Laravel class. Here's an extract of my code:
private $data;
private $userID;//Set property
function __construct()
{
$this->middleware('auth');//Call middleware
$this->userID = Auth::id();//Define property as user ID
}
public function index() {
return view('');
}
public function MyTestMethod() {
echo $this->userID;//This returns null
echo Auth::id();//This works & returns the current user ID
}
I am logged in and have included use Illuminate\Support\Facades\Auth; in the class thus the code works, but only when accessing Auth in methods - else it returns a null value.
Most odd, I can't work out what is causing this. Any thoughts much appreciated as ever. Thanks in advance!
In Laravel Laravel 5.3.4 or above, you can't access the session or authenticated user in your controller's constructor, since the middlware isn't runnig yet.
As an alternative, you may define a Closure based middleware directly in your controller's constructor.:
try this :
function __construct()
{
$this->middleware(function ($request, $next) {
if (!auth()->check()) {
return redirect('/login');
}
$this->userID = auth()->id(); // or auth()->user()->id
return $next($request);
});
}
another alternative solution go you your base controller class and add __get function like this :
class Controller
{
public function __get(string $name)
{
if($name === 'user'){
return Auth::user();
}
return null;
}
}
and now if your current controller you can use it like this $this->user:
class YourController extends Controller
{
public function MyTestMethod() {
echo $this->user;
}
}
You should try this :
function __construct() {
$this->userID = Auth::user()?Auth::user()->id:null;
}
OR
public function __construct()
{
$this->middleware(function ($request, $next) {
$this->userID = Auth::user()->id;
return $next($request);
});
}

Class App not found error in (Laravel 5.4)

I want to insert the remark field into the database, but it seems that it doesn't work. So instead, I get the following error.
Class 'App\Job' not found
Jobs.php
class Job extends Model
{
public function index()
{
return view('create-job');
}
public function user()
{
return $this->belongsTo('App\User');
}
}
JobController.php
class JobController extends Controller
{
public function postCreateJob(Request $request)
{
// Validation
$post = new Job();
$post->remarks = $request['remarks'];
$request->job()->save($post);
return redirect()->route('home');
}
public function index()
{
return view('create-job');
}
}
Your model name is Jobs.
Need to change the name of the model to Job
Hope this helps.

Laravel passing username parameter to controller from user.blade.php

Hi on my website I have profile with username parameter root/user/{username}. I was planning to add button to block the user. My problem is that when other user click block button, the button do stuffs in the Check.php controller but it doesn't pass the user/{username} parameter that I need in if statements. My question is how I can pass the {username} parameter from my user.blade.php to the Check.php controller?
As we are not seeing any code here, it seems that to do what you need, you just have to create a route pointing to your controller method and eventually a route to redirect your users when successufully blocked:
Route::get('user/block/{username}', 'BlockUserController#block');
Route::get('userBlocked', 'BlockUserController#blocked');
And the controller itself:
class BlockUserController extends Controller {
public function block($username)
{
$user = User::where('username', $username);
$user->blocked = true;
$user->save();
return Redirect::to('userBlocked');
}
public function blocked($username)
{
return View::make('user.blocked');
}
}
And then if you click the button pointing to the route:
http://application.com/user/block/user3398940
It will be blocked.
If you want to go a little more advanced in Laravel, you can use dependency injection and remove some code from your controller:
class BlockUserController extends Controller {
private $user;
public function __construct(User $user)
$this->user = $user;
}
public function block($username)
{
if ($user->block($username))
{
return Redirect::to('userBlocked');
}
return Redirect::back()->with('message', 'User not found');
}
public function blocked($username)
{
return View::make('user.blocked');
}
}
And your user model would have to have a block method:
class User extends Eloquent {
public function block($username)
{
if ($user = $this->newQuery()->where('username', $username))
{
$user->blocked = true;
return $user->save();
}
return false;
}
}

Categories