Laravel Trait Doesn't Excite - php

I've a trait function that updating a report, i've done its route and its namespace also im using it in the controller everything is right but when i submit it doesn't run and the page only refreshs
Trait Function
<?php
namespace App\Http\Controllers\Permit\Trait;
use App\Models\Log;
use App\Models\Permit;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Redirect;
trait HazardsInfo
{
public function HazardsInfo(Request $request, $id)
{
dd($request);
$permit = Permit::findOrFail($id);
$permit->Update([
'gaurd_names' => $request->gaurd_names,
]);
Log::create([
'permit_id' => $permit->id,
'created_by' => Auth::user()->id,
'status' => 'og-complete'
]);
return Redirect::to("/permit/{$id}/edit")->withSuccess('Hazards Has Been Updated');
}
}
Route
Route::post('/permit/{permit}/edit', [PermitController::class, 'HazardsInfo'])->name('permit.HazardsInfo');
blade form
<form action="{{ route('permit.HazardsInfo', $permit->id) }}">
#if (Session::has('success'))
<div class="alert alert-success w-25 ms-2 text-center">
{{ Session::get('success') }}
</div>
#endif
<input type="text" name="gaurd_names">
<button type="submit" class="btn btn-success btn-label right ms-auto nexttab nexttab" data-nexttab=""><i
class="ri-arrow-left-line label-icon align-middle fs-16 ms-2"></i>
Submit</button>
</form>

Related

Laravel - Method Illuminate\Http\Request::request does not exist

I have created a view to create new courses 'create.blade.php'. And I am trying to store this data in the DB however I am getting the following error:
BadMethodCallException Method Illuminate\Http\Request::request does
not exist.
I am not sure what is causing the error as I have referred to the the request namespace in my controller. See below;
CoursesController.php;
<?php
namespace App\Http\Controllers\Admin;
use Gate;
use App\User;
use App\Course;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Input;
class CoursesController extends Controller
{
public function __construct()
{
//calling auth middleware to check whether user is logged in, if no logged in user they will be redirected to login page
$this->middleware('auth');
}
public function index()
{
if(Gate::denies('manage_courses')){
return redirect(route('home'));
}
$courses = Course::all();
return view('admin.course.index')->with('course', $courses); //pass data down to view
}
public function create()
{
if(Gate::denies('create_courses')){
return redirect(route('home'));
}
$courses = Course::all()->pluck('title');
$instructors = User::all()->pluck('name', 'id'); //defining instructor variable
return view('admin.course.create', compact('instructors')); //passing instructor to view
}
public function store(Request $request)
{
$course = Course::create($request->all()); //request all the data fields to store in DB
$course->courses()->sync($request->request('courses', [])); //
if($course->save()){
$request->session()->flash('success', 'The course ' . $course->title . ' has been created successfully.');
}else{
$request->session()->flash('error', 'There was an error creating the course');
}
return redirect()->route ('admin.courses.index');
}
}
Create.blade.php
#extends('layouts.app')
#section('content')
<div class="row justify-content-center">
<div class="col-md-8">
<div class="card">
<div class="card-header">Create Course</div>
<div class="card-body">
<form method="POST" action="{{ route('admin.courses.store') }}" enctype="multipart/form-data">
#csrf
<div class="form-group">
<label class="required" for="name">Course Title</label>
<input class="form-control {{ $errors->has('title') ? 'is-invalid' : '' }}" type="text" name="title" id="id" value="{{ old('title', '') }}" required>
#if($errors->has('name'))
<div class="invalid-feedback">
{{ $errors->first('name') }}
</div>
#endif
</div>
<div class="form-group">
#if (Auth::user()->isAdmin())
{!! Form::label('Instructor', 'Instructor', ['class' => 'control-label']) !!}
{!! Form::select('Instructor[]', $instructors, Input::get('Instructor'), ['class' => 'form-control select2', 'multiple' => 'multiple']) !!}
#if($errors->has('Instructor'))
{{ $errors->first('Instructor') }}
</p>
#endif
</div>
<div class="form-group">
<button class="btn btn-danger" type="submit">
Save
</button>
</div>
</div>
#endif
</form>
</div>
</div>
#endsection
I am new to laravel so i would appreciate any help. Thanks.
The error message
BadMethodCallException Method Illuminate\Http\Request::request does
not exist
speaks to an attempt to call a method/function named request on the Illuminate\Http\Request class, and that function not existing.
it looks like you are indeed trying to use a request() method here:
$course->courses()->sync($request->request('courses', []));
You most likely want the input() method instead, which would get data posted as 'courses'.
$course->courses()->sync($request->input('courses', []));
as described at https://laravel.com/docs/master/requests#input-trimming-and-normalization
I hope this helps!
change
$course->courses()->sync($request->input('courses', []));

login autorization error getting Undefined variable: erros

I'm start learning laravel and want to create sample login authorization system on my html template. I watched a tutorial and when i do everything that was in video i get error Undefined variable: erros.
I'm new and I don't know good PHP but i want to learn while creating a website I know a little.
my rout code is my route code :
this is route for my login code
Route::get ('/main', 'MainController#index');
Route::get ('/main/checklogin', 'MainController#checklogin');
Route::get ('/main/successlogin', 'MainController#successlogin');
Route::get ('/main/logout', 'MainController#logout');
1.my login code
<div class="login slide-up">
<div class="center">
<h2 class="form-title" id="login"><span>sign</span>in</h2>
#if (isset(Auth::user()->email))
<script>window.location="/main/successlogin"</script>
#endif
#if ($message = Session::get('error'))
<div class ="alert alert-danger alert-block">
<button type="button" class="close" data-dismiss="alert">X</button>
<strong>{{$message}}</strong>
#endif
<form method="get" action="{{ url('/main/checklogin')
}}">
#if(count($errors) >0 )
<div class="alert alert-danger">
<ul>
#foreach($erros->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
<form method="get" action="{{ url('/main/checklogin')
}}">
{{ csrf_field()}}
<div class="form-holder">
<input type="email" class="input" placeholder="email" />
<input type="password" class="input" placeholder="password" />
</div>
<button class="submit-btn">Sign in</button>
</div>
2.my successlogin code
<html>
<body>
#if (issets(auth::user()->email))
<p>gamarjoba {{Auth::user()->email}}}</p>
<a href="{{ url('/main/logout') }}" > logout </a>
else
<script>windows.location = "/main"; </script>
#endif
</body>
</html>
my main controller
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Validator;
use Auth;
class MainController extends Controller
{
function index()
{
return view('front/login');
}
function checklogin(Request $request)
{
$this->validate($request, [
'email' => 'required|email',
'password' => 'required|alphaNum|min:4'
]);
$user_data = array(
'email' => $request -> get('email'),
'password' => $request -> get('password')
);
if (Auth::attempt($user_data))
{
return redirect('main/successlogin');
}
else
{
return back()->with('error', 'wrong Login Details');
}
}
function successlogin()
{
return view('successlogin');
}
function logout()
{
Auth::logout();
return redirect('main');
}
}
Laravel made this easy:
Run php artisan make:auth

Submitting a request in Laravel and sending mail

I am trying to submit a form and send an email based on data submitted through the form, but it doesn't seem to be working because I don't get back the success message.
Controller
public function contact(Request $request)
{
$request = request()->validate([
'name' => 'required',
'email' => 'required| email',
'message' => 'required | max:1000',
]);
Mail::to('support#mail.com')->send(new contact($request));
return redirect()->back()->with("success", "You email has successfully been sent");
}
Form
#if (session('error'))
<div class="alert alert-danger">
{{ session('error') }}
</div>
#endif
#if (session('success'))
<div class="alert alert-success">
{{ session('success') }}
</div>
#endif
<form action="/contact" method="POST">
#csrf
<div class="col-md-12">
<input type="text" placeholder="Full Name" required name="name">
</div>
<div class="col-md-8">
<input type="text" placeholder="email" required name="email">
</div>
<div class="col-md-2">
<textarea name="message"></textarea>
</div>
<div class="col-md-12">
<button class="btn btn-black no-margin-bottom btn-small"
type="submit">Contact</button>
</div>
</form>
Route
`Route::post('/contact', 'HomeController#contact');`
If you're being redirected back to the form page without error messages or your sucess flash message then I am inclined to think the problem is in your template. Assuming you are using the laracasts/flash package your method should look like this
public function contact(Request $request)
{
$request = request()->validate([
'name' => 'required',
'email' => 'required| email',
'message' => 'required | max:1000'
]);
Mail::to('support#mail.com')->send(
new contact($request)
);
return redirect()->back()->with("success", "You email has successfully been sent");
}
redirect()->with() adds data to the session but it doesn't display a message unless you manually do so in the template like this
#if (session('sucess'))
<div class="alert alert-success">
{{ session('success') }}
</div>
#endif
Make sure you're displaying errors properly in your form, replace your session('error') block with the following:
#if($errors->any())
<div class="alert alert-danger">
<ul>
#foreach($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
In your controller:
use App\Mail\Contact;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Mail;
class HomeController extends Controller
{
// ...
public function contact(Request $request)
{
// Note I'm not overwriting the $request variable.
// This method returns an array of the validated data.
$request->validate([
'name' => 'required',
'email' => 'required|email',
'message' => 'required|max:1000'
]);
Mail::to('support#mail.com')->send(new Contact($request));
return back()->with('success', 'Your email has successfully been sent');
}
}
Your mail class should look something like this:
namespace App\Mail;
use Illuminate\Http\Request;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
class Contact extends Mailable
{
use Queueable, SerializesModels;
protected $request;
public function __construct(Request $request)
{
$this->request = $request;
}
public function build()
{
// The request instance must be passed to the view...
return $this->markdown('emails.contact', [
'request' => $this->request
]);
}
}
You can now use the Request object in your email markdown (emails.contact). For example:
**Name**<br>
{{ $request->input('name') }}
**Email**<br>
{{ $request->input('email') }}
**Message**<br>
{{ $request->input('message') }}

Laravel 5.1 $this->validate(...) throws error

I'm trying to add validation to my resource controller using the laravel's validation (http://laravel.com/docs/5.1/validation) but I get this error:
ErrorException in ValidatesRequests.php line 30:
Argument 1 passed to App\Http\Controllers\Controller::validate() must be an
instance of Illuminate\Http\Request,
instance of Illuminate\Support\Facades\Request given,
called in
/Users/lextoc/Documents/Sites/partyrecycler/app/
Http/Controllers/MarkerController.php on line 30 and defined
This is the controller:
namespace App\Http\Controllers;
use Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Marker;
class MarkerController extends Controller
{
...
public function create()
{
return view('markers.create');
}
public function store(Request $request)
{
$this->validate($request, [
'name' => 'required|max:255',
'x' => 'required',
'y' => 'required',
]);
$marker=Request::all();
Marker::create($marker);
return redirect('markers');
}
...
}
And the view:
<h1>Create marker</h1>
#if (count($errors) > 0)
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
{!! Form::open(array('route' => 'markers.store')) !!}
{!! csrf_field() !!}
<div>
Name
<input type="text" name="name">
</div>
<div>
x
<input type="text" name="x">
</div>
<div>
y
<input type="text" name="y">
</div>
<div>
<button type="submit">Create</button>
</div>
{!! Form::close() !!}
I don't know why it's using the wrong Request class, and why are there two being used in the controller?
The error is due to your include headers:
Try
use Illuminate\Http\Request;
Instead of
use Request;
Example:
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Marker;

Laravel : BadMethodCallException Method [store] does not exist

I just downloaded and started a new project with the latest Laravel 4.2. When trying to submit a form I get the following error : BadMethodCallException Method [store] does not exist
Here are my files : controller - admin/AdminController
<?php
namespace admin;
use Illuminate\Support\Facades\View;
use App\Services\Validators\ArticleValidator;
use Input, Notification, Redirect, Sentry, Str;
class AdminController extends \BaseController {
public function index() {
if (Input::has('Login')) {
$rules = array(
'email' => 'required',
'password' => 'required|min:3',
'email' => 'required|email|unique:users'
);
$validator = Validator::make(Input::all(), $rules);
if ($validator->fails()) {
return Redirect::to('admin\AdminController')->withErrors($validator);
} else {
// redirect
Session::flash('message', 'Successfully created user!');
return Redirect::to('admin\AdminController');
}
}
$data['title'] = ADMIN;
return View::make('admin.index', $data);
}
}
View page - admin/index.blade.php
<div class="container">
{{ Form::open(array('url' => ADMIN,'id' => 'login')) }}
<div id="icdev-login-wrap">
<div class="raw align-center logoadmin">{{ HTML::image('images/logo.png') }}</div>
<div id="icdev-login">
<h3>Welcome, Please Login</h3>
<div class="mar2_bttm input-group-lg"><input type="text" class="form-control loginput" placeholder="Email" name="email"></div>
<div class="mar2_bttm input-group-lg"><input type="password" class="form-control loginput" placeholder="Password" name="password"></div>
<div ><input type="submit" class="btn btn-default btn-lg btn-block cus-log-in" value="Login" /></div>
<div class="row align-center forgotfix">
<input type="hidden" name="Login" value="1">
</div>
</div>
<div>
</div>
</div>
{{ Form::close() }}
</div>
The error message tells you what the problem is: the method called store() doesn’t exist. Add it to your controller:
<?php
namespace admin;
use Illuminate\Support\Facades\View;
use App\Services\Validators\ArticleValidator;
use Input, Notification, Redirect, Sentry, Str;
class AdminController extends \BaseController {
public function index()
{
// leave code as is
}
public function store()
{
// this is your NEW store method
// put logic here to save the record to the database
}
}
A couple of points:
Use camel-casing for name spaces (i.e. namespace admin should be namespace Admin)
Read the Laravel documentation on resource controllers: http://laravel.com/docs/controllers#resource-controllers
You can also automatically generate resource controllers with an Artisan command. Run $ php artisan make:controller ItemController, replacing ItemController with the name of the controller, i.e. ArticleController or UserController.

Categories