Method [all] does not exist in Laravel 5.2 - php

just now I get this issues that is bothering me.
the error in code after validator::make in update function.
BadMethodCallException in Controller.php line 107: Method [all] does
not exist.
This is the full code from BooksController
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Redirect;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\book;
class BooksController extends Controller
{
/**
* Display a listing of the resource.
*
* #return Response
*/
public function index()
{
$book = BooksController::all();
return view('book.index')->with('book', $book);
}
/**
* Show the form for creating a new resource.
*
* #return Response
*/
public function create()
{
return view('book.create');
}
/**
* Store a newly created resource in storage.
*
* #return Response
*/
public function store()
{
$rules = array(
'judul' => 'required',
'author' => 'required',
'penerbit' => 'required'
);
$validator = Validator::make(Input::all(), $rules);
// process the login
if ($validator->fails()) {
return Redirect::to('book/create')
->withErrors($validator)
->withInput(Input::except('password'));
} else {
// store
$book = new book;
$book ->judul = Input::get('judul');
$book ->author = Input::get('author');
$book ->penerbit = Input::get('penerbit');
$book ->save();
// redirect
Session:flash('message', 'Berhasil membuat buku!');
return Redirect::to('book');
}
}
/**
* Display the specified resource.
*
* #param int $idate
* #return Response
*/
public function show($id)
{
$book = books::find($id);
return view('book.show')
->with('book', $book);
}
/**
* Show the form for editing the specified resource.
*
* #param int $id
* #return Response
*/
public function edit($id)
{
$book = books::find($id);
return view('book.edit')
->with('book', $book);
}
/**
* Update the specified resource in storage.
*
* #param int $id
* #return Response
*/
public function update($id)
{
$rules = array(
'judul' => 'required',
'author' => 'required',
'penerbit' => 'required'
);
$validator = Validator::make(Input::all(), $rules);
if ($validator->fails()) {
return Redirect::to('book/' . $id . '/edit')
->withErrors($validator)
->withInput(Input::except('password'));
} else {
// simpan
$book = books::find($id);
$book->judul = Input::get('judul');
$book->author = Input::get('author');
$book->penerbit = Input::get('penerbit');
$book->save();
// redirect
Session::flash('message', 'Berhasil mengganti info buku!');
return Redirect::to('book');
}
}
/**
*
* #param int $id
* #return Response
*/
public function destroy($id)
{
$book = books::find($id);
$book ->delete();
//redirect
Session::flash('message', 'Berhasil menghapus buku!');
return Redirect::to('book');
}
}

try this use Validator; instead of
use Illuminate\Support\Facades\Validator;
convert user Input::all() to input()->all() or request()->all()

Related

Laravel image save as .tmp in the db even though the file uploaded in the correct folder

I'm trying to add a user to the database in Laravel.
following is my User Model.
<?php
namespace App\Models;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Spatie\Permission\Traits\HasRoles;
class User extends Authenticatable implements MustVerifyEmail {
use HasFactory, Notifiable, HasRoles;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'first_name',
'last_name',
'image_id',
'country_id',
'email',
'password',
'gender',
'date_of_birth',
'region_id',
'role_id',
'is_email_verified'
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password',
'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
}
And this is my User Controller.
<?php
namespace App\Http\Controllers\Admin;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\User;
use Spatie\Permission\Models\Role;
use DB;
use Hash;
class UserController extends Controller {
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index(Request $request) {
$data = User::orderBy('id','DESC')->paginate(5);
return view('admins.users.index',compact('data'))
->with('i', ($request->input('page', 1) - 1) * 5);
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create() {
$roles = Role::pluck('name','name')->all();
return view('admins.users.create',compact('roles'));
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request) {
$data = $request->input('roles');
foreach($data as $key => $value) {
$key = 'data' . $key;
$$key = $value;
}
$roleid=$data0;
if($roleid=='Admin') {
$roleid='1';
} else if($roleid=='Regional Admin') {
$roleid='2';
} else {
$roleid='3';
}
$request->merge(['role_id' => ''.$roleid.'']);
$request->merge(['gender' => 'M']);
$request->merge(['date_of_birth' => '1992-01-11']);
$this->validate($request, [
'first_name' => 'required',
'last_name' => 'required',
'email' => 'required|email|unique:users,email',
'password' => 'required|same:confirm-password',
'roles' => 'required',
'image_id' => 'image|mimes:jpeg,png,jpg,gif,svg|max:2048',
'role_id'=>'required',
'gender'=>'required',
'date_of_birth'=>'required'
]);
if ($image = $request->file('image_id')) {
$destinationPath = 'propics/';
$profileImage = date('YmdHis') . "." . $image->getClientOriginalExtension();
$image->move($destinationPath, $profileImage);
$input['image_id'] = $profileImage;
$request->merge(['image_id' => $profileImage]);
}
//$input['role_id']=$request->input('roles');
dd($request->all());
$input = $request->all();
$input['password'] = Hash::make($input['password']);
$user = User::create($input);
$user->assignRole($request->input('roles'));
return redirect()->route('users.index')
->with('success','User created successfully');
}
/**
* Display the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function show($id) {
$user = User::find($id);
return view('admins.users.show',compact('user'));
}
/**
* Show the form for editing the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function edit($id) {
$user = User::find($id);
$roles = Role::pluck('name','name')->all();
$userRole = $user->roles->pluck('name','name')->all();
return view('admins.users.edit',compact('user','roles','userRole'));
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param int $id
* #return \Illuminate\Http\Response
*/
public function update(Request $request, $id) {
$this->validate($request, [
'name' => 'required',
'email' => 'required|email|unique:users,email,'.$id,
'password' => 'same:confirm-password',
'roles' => 'required'
]);
$input = $request->all();
if(!empty($input['password'])) {
$input['password'] = Hash::make($input['password']);
} else {
$input = array_except($input,array('password'));
}
$user = User::find($id);
$user->update($input);
DB::table('model_has_roles')->where('model_id',$id)->delete();
$user->assignRole($request->input('roles'));
return redirect()->route('admins.users.index')
->with('success','User updated successfully');
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function destroy($id) {
User::find($id)->delete();
return redirect()->route('admins.users.index')
->with('success','User deleted successfully');
}
}
Now my question is that this stores my users in the DB perfectly but the user image stores as .tmp.
The file also get uploaded into the correct folder, but when it stores in the DB it stores as,
C:\xampp\tmp\phpA031.tmp
instead of .png or .jpg
Where should I correct my code?
public function store(Request $request){
$post = new Post([
'title'=>$request->get('title'),
'description'=>$request->get('description')
]);
$imageName = $request->title.'.png';
$request->image->move(public_path('images/posts'),$imageName);
$post->save();
return redirect()->back();
}
now you create view and create 3 input fields: name title (text), description (textarea) and image (file)

Notifications for comments not working in laravel

error
enter image description here
I am trying to send notifications of the event when some likes and comment on his post, notifications for comments and likes working
here is my notification class.
i have error in my CommentController if ($event->user_id != $comment->user_id)
class NewCommentEvent extends Notification
{
use Queueable;
protected $comment;
/**
* Create a new notification instance.
*
* #return void
*/
public function __construct($comment)
{
$this->comment = $comment;
}
/**
* Get the notification's delivery channels.
*
* #param mixed $notifiable
* #return array
*/
public function via($notifiable)
{
return ['database'];
}
/**
* Get the array representation of the notification.
*
* #param mixed $notifiable
* #return array
*/
public function toDatabase($notifiable)
{
return [
'comment' => $this->comment,
'event' => Event::find($this->comment->event_id),
'user' => User::find($this->comment->user_id)
];
}
/**
* Get the array representation of the notification.
*
* #param mixed $notifiable
* #return array
*/
public function toArray($notifiable)
{
return [
//
];
}
}
My controller function code for notifications on comments
public function store(CommentRequest $request)
{
$event = Event::findOrFail($request->event_id);
Comment::create([
'comment' => $request->comment,
'user_id' => Auth::id(),
'event_id' => $event->id
]);
if ($event->user_id != $comment->user_id) {
$user = User::find($event->user_id);
$user->notify(new NewCommentEvent($comment));
}
Toastr::success('Comment post with success','', ["positionClass" => "toast-top-center"]);
return redirect()->back();
}
my CommenRequest
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Support\Facades\Auth;
class CommentRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public function authorize()
{
return Auth::check();
}
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
return [
'comment' => 'required|max:2000',
];
}
}
In your controller: the variable $comment is not defined.
From Laravel docs:
The create method returns the saved model instance.
so the solution is:
$comment = Comment::create([
'comment' => $request->comment,
'user_id' => Auth::id(),
'event_id' => $event->id
]);
you have not defined your $comment, you just created a comment. This is throwing the error
$comment = Comment::create([
.
.
]);
This will fix your issue
The error message was clear. $comment is undefined. Replace your controller code with the follow:
public function store(CommentRequest $request)
{
$event = Event::findOrFail($request->event_id);
// defined comment here
$comment = Comment::create([
'comment' => $request->comment,
'user_id' => Auth::id(),
'event_id' => $event->id
]);
if ($event->user_id != $comment->user_id) {
$user = User::find($event->user_id);
$user->notify(new NewCommentEvent($comment));
}
Toastr::success('Comment post with success','', ["positionClass" => "toast-top-center"]);
return redirect()->back();
}

Notifications wont work Laravel

i've implemented notifications on my app.And they were working fine until yesterday out of the blue the stopped working.now when i click on the route that enables the notification it just keeps loading this is the store method on my controller where i check if the email notifications are enabled and if they are the user should recieve an email everytime a project is published
public function store(Request $request){
$this->validate(request(), [
'title' => 'required|max:255|unique:projects',
'body' => 'required|max:1000',
// 'tutorial' => 'required|max:1000',
'avatar' => 'required|mimes:jpeg,bmp,png',
'zip_file' => 'required|mimes:zip,rar',
]);
$user = User::all();
$profiles_storage = storage_path('app/avatars/');
$project = new Project;
$project -> user_id = auth()->id();
$project -> title = request('title');
$project -> body = request('body');
$project -> tutorial = request('tutorial');
$project -> views = '0';
$project -> downloads = '0';
$project -> alternative_text = config('app.name').' '.request('title').' '.'project';
$profile = request()->file('avatar');
// $profile->store('profiles');
$project->image = $profile->hashName();
$image = Image::make($profile->getRealPath());
$image->fit(640, 360, function ($constraint)
{ $constraint->upsize();})->save($profiles_storage.$profile->hashName());
request()-> file('zip_file')->store('zip_files');
$project -> zip_file = request()->file('zip_file')->hashName();
$project -> save();
$category = $request->input('categories');
$project->categories()->sync($category);
foreach ($user as $u) {
if ($u->email_notifications != 0) {
$u->notify(new ProjectPublished($project));
}
}
session()->flash('message',"{$project->title}".' created');
return redirect('/admin/projects');
}
and this is the ProjectPublished.php
<?php
namespace App\Notifications;
use App\User; use App\Project; use Illuminate\Bus\Queueable; use Illuminate\Notifications\Notification; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Notifications\Messages\MailMessage;
class ProjectPublished extends Notification { use Queueable; protected $project;
/**
* Create a new notification instance.
*
* #return void
*/
public function __construct(Project $project)
{
$this->project = $project;
}
/**
* Get the notification's delivery channels.
*
* #param mixed $notifiable
* #return array
*/
public function via($notifiable)
{
return ['mail'];
}
/**
* Get the mail representation of the notification.
*
* #param mixed $notifiable
* #return \Illuminate\Notifications\Messages\MailMessage
*/
public function toMail($notifiable)
{
return (new MailMessage)
->greeting('Hello there')
->subject('New Project:'.$this->project->title)
->line('As requested we are letting you know that a new project was published at Rek Studio')
->action('Check it out', url('projects/'.$this->project->title));
}
/**
* Get the array representation of the notification.
*
* #param mixed $notifiable
* #return array
*/
public function toArray($notifiable)
{
return [
//
];
}
}
can anyone help me out?

Using named routes in protected methods in Laravel Controller

In my LoginController I have:
protected $redirectTo = '';
I then do this:
public function boot()
{
Parent::boot();
$this->redirectTo = route('org.home');
$this->logoutTo = route('user.login');
}
But in a method in the controller I check and I get a BLANK value from $this->redirectTo
protected function authenticated(Request $request, $user)
{
dd($this->redirectTo);
}
How do I make the value of this variable dynamic and use the route name to assign its value?
Here is my whole controller based on the comments below:
<?php
namespace App\Http\Controllers\Auth;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
class LoginController extends Controller
{
/*
|--------------------------------------------------------------------------
| Login Controller
|--------------------------------------------------------------------------
|
| This controller handles authenticating users for the application and
| redirecting them to your home screen. The controller uses a trait
| to conveniently provide its functionality to your applications.
|
*/
use AuthenticatesUsers;
/**
* Which Authentication Guard we are working with
*
* #var string
*/
protected $guard = 'user';
/**
* URI where we redirect to after registration
*
* #var string
*/
protected $redirectTo = '';
/**
* URI where we redirect to after logout
*
* #var string
*/
protected $logoutTo = '';
/**
* LoginController constructor.
*/
public function __construct()
{
//
}
/**
* Bootstrap any application services.
*
* #return void
*/
public function boot()
{
Parent::boot();
$this->redirectTo = route('org.home');
$this->logoutTo = route('user.login');
}
/**
* Show the application's login form.
*
* #return \Illuminate\Http\Response
*/
public function showLoginForm()
{
return view('auth.user.main.login');
}
/**
* Log the user out of the application.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function logout(Request $request)
{
Auth::guard($this->guard)->logout();
$request->session()->flush();
$request->session()->regenerate();
if ($request->ajax()) {
return response()->json([
'type' => 'success',
'message' => trans('auth.logout_ok')
]);
} else {
return redirect($this->logoutTo ?: '/');
}
}
/**
* The user has been authenticated.
*
* #param \Illuminate\Http\Request $request
* #param mixed $user
* #return mixed
*/
protected function authenticated(Request $request, $user)
{
// If this user belongs to a partner
if ($user->isPartner()) {
// And the partner is active, then continue
if (!$user->partner->isActive()) {
// Else respond with an error
$error = [
'type' => 'error',
'message' => trans('messages.partner_inactive')
];
if ($request->ajax()) {
return response()->json($error);
} else {
return redirect()->back()->withErrors($error);
}
}
}
dd($this->redirectTo);
// Set up the user's session
$this->setupSession();
if ($request->ajax()) {
return response()->json([
'type' => 'success',
'user' => auth()->check(),
'intended' => $this->redirectPath(),
'message' => trans('auth.logout_ok')
]);
} else {
return redirect()->intended($this->redirectPath());
}
}
/**
* Send the response after the user was authenticated.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
protected function sendLoginResponse(Request $request)
{
$request->session()->regenerate();
$this->clearLoginAttempts($request);
if ($this->authenticated($request, $this->guard()->user())) {
return true;
} else {
if ($request->ajax()) {
return response()->json([
'type' => 'error',
'user' => auth()->check(),
'intended' => $this->redirectPath(),
'message' => trans('auth.not_login')
]);
} else {
return redirect()->intended($this->redirectPath());
}
}
}
/**
* Get the failed login response instance.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\RedirectResponse
*/
protected function sendFailedLoginResponse(Request $request)
{
$errors = [$this->username() => trans('auth.failed')];
if ($request->expectsJson()) {
return response()->json($errors, 422);
}
return redirect()->back()
->withInput($request->only($this->username(), 'remember'))
->withErrors($errors);
}
/**
* Set up all session variables here
*/
private function setupSession()
{
// session()->put('user', Auth::user());
}
}
I had to put my assignments here
public function __construct()
{
$this->redirectTo = route('org.home');
$this->logoutTo = route('user.login');
}

Laravel Roles without pivot table

I am student and i am new with Laravel and i have this UserController which used to assign multi Roles to User (using pivot table user_role) but i want to assign one role to each user (without pivot table) so i added role_id foreign in table user but i dont know what to change in UserController file.
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\User;
use App\Role;
use DB;
use Hash;
class UserController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index(Request $request)
{
$data = User::orderBy('id','DESC')->paginate(5);
return view('users.index',compact('data'))
->with('i', ($request->input('page', 1) - 1) * 5);
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
$roles = Role::pluck('display_name','id');
return view('users.create',compact('roles'));
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$this->validate($request, [
'name' => 'required',
'email' => 'required|email|unique:users,email',
'password' => 'required|same:confirm-password',
'roles' => 'required'
]);
$input = $request->all();
$input['password'] = Hash::make($input['password']);
$user = User::create($input);
foreach ($request->input('roles') as $key => $value) {
$user->attachRole($value);
}
return redirect()->route('users.index')
->with('success','User created successfully');
}
/**
* Display the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function show($id)
{
$user = User::find($id);
return view('users.show',compact('user'));
}
/**
* Show the form for editing the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function edit($id)
{
$user = User::find($id);
$roles = Role::pluck('display_name','id');
$userRole = $user->roles->pluck('id','id')->toArray();
return view('users.edit',compact('user','roles','userRole'));
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param int $id
* #return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
$this->validate($request, [
'name' => 'required',
'email' => 'required|email|unique:users,email,'.$id,
'password' => 'same:confirm-password',
'roles' => 'required'
]);
$input = $request->all();
if(!empty($input['password'])){
$input['password'] = Hash::make($input['password']);
}else{
$input = array_except($input,array('password'));
}
$user = User::find($id);
$user->update($input);
DB::table('role_user')->where('user_id',$id)->delete();
foreach ($request->input('roles') as $key => $value) {
$user->attachRole($value);
}
return redirect()->route('users.index')
->with('success','User updated successfully');
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function destroy($id)
{
User::find($id)->delete();
return redirect()->route('users.index')
->with('success','User deleted successfully');
}
}
and you can find all the code here:
http://itsolutionstuff.com/post/laravel-52-user-acl-roles-and-permissions-with-middleware-using-entrust-from-scratch-tutorialexample.html
this mean so much to me if you help me and thanks.

Categories