I am trying to store data into the database, but the error I'm getting is:
Call to undefined method App\User::events()
public function store(Request $request)
{
$this->validate($request, [
'title' => 'required',
'slug' => 'required|unique:events',
'body' => 'required',
'date' => 'date_format:M-d-y H:i:s',
'time' => 'required'
]);
$request->user()->events()->create($request->all());
return redirect('/backend/blog')->with('message', 'Your event was created successfully');
}
Try this:
public function store(Request $request)
{
$this->validate($request, [
'title' => 'required',
'slug' => 'required|unique:events',
'body' => 'required',
'date' => 'date_format:M-d-y H:i:s',
'time' => 'required'
]);
$user = User::create($request->all()); // create the user
event(new UserRegistered($user)); // Add your own event class name.
return redirect('/backend/blog')->with('message', 'Your event was created successfully');
}
Note: Assuming that you have created the UserRegistered event. And call it by event helper method.
It seems like you do not have any events() relationship in you User model.
Assuming you have Event model, you can write like in User model:
public function events()
{
return $this->hasMany(Event::class);
}
Related
I am getting error for undefined method which is defined inside my User model.
My controller:
$inputs = request()->validate([
'title' => 'required|min:8|max:255',
'post_image' => 'file',
'body' => 'required'
]);
auth()->user()->posts()->create($inputs);
My Post model:
public function user() {
return $this->belongsTo('App\Models\User');
}
My User model:
public function posts() {
return $this->hasMany('App\Models\Post');
}
correct your relationship
public function posts() {
return $this->hasMany(Post::class);
}
First your posts relationship is wrong, it must be hasMany NOT belongsTo
public function posts() {
return $this->hasMany(User::class);
}
Then it should work.
You can also try to create the model in a different way:
$validated = request()->validate([
'title' => 'required|min:8|max:255',
'post_image' => 'file',
'body' => 'required'
]);
// Here you should check if $validated has all required fields
// because some could fail, in that case aren't in the array
Post::create([
'title' => $validated['title'],
'user_id' => auth()->id, // or auth()->user->id
'post_image' => $validated['post_image'],
'body' => $validated['body'],
]);
Laravel Validation Docs
This is contact form. I would like to recive email and save this data to my mysql. I use Laravel. Email function works good. but There is a problem. I would like to store all data at "function complete".
I validate all data at "function confirm" This is confirm screen page so user still not submit yet. I tried to write code like this at "function complete" but error say "Undefined variable: request" Could you teach me how to fix my code please?
public function confirm(Request $request)
{
$rules = [
'title' => 'required',
'search' => 'required',
'amount' => 'required|integer',
'email' => 'required|email',
'body' => 'required',
];
$this->validate($request, $rules);
$data = $request->all();
$request->session()->put($data);
return view('mail.confirm', compact("data"));
}
public function complete()
{
$data = $request->all(); # 3)
$request->session()->put($data); # 4)
Contact::create($request->all());
$data = session()->all();
Mail::send([ ・・・
You have to pass the parameter type $request as you did in confirm function.In your complete function, you don't declare $request variable and accessing it without declaration
public function confirm(Request $request)
{
$rules = [
'title' => 'required',
'search' => 'required',
'amount' => 'required|integer',
'email' => 'required|email',
'body' => 'required',
];
$this->validate($request, $rules);
$data = $request->all();
// setting session key value for you data
$request->session()->put('data',$data);
return view('mail.confirm', compact("data"));
}
/*
* complete page
*/
public function complete(Request $request)
{
// after confirm button click get data from session with key '#data' ;
$data = $request->session()->pull('data');
// get token value in variable and remove from data set so we can use mass assignement
$token = array_shift($data);
// creating record
$Contact = Contact::create($data);
Mail::send(['text' => 'mail.temp'], $data, function($message) use($data){
$message->to($data["email"])->bcc('lara_admin#sakura.ne.jp')->from('1110.ne.jp')->subject('thnak you。');});
Mail::send(['text' => 'mail.admintemp'], $data, function($message) use($data){
$message->to('lara_admin#sakura.ne.jp')->from('emailconf#.ne.jp')->subject('you got order');});
$data = session()->regenerateToken();
return view('mail.complete');
}
Hi im trying to upload image into database when i do this all its gave error like this.
(1/1) BadMethodCallException
Method getClientOrignalName does not exist.
<form action="{{route('post.store')}}" method="post" enctype="multipart/form-data">**strong text**
public function store(Request $request)
{
$this->validate($request,[
'title' => 'required|max:255',
'content' => 'required',
'feature' => 'required|image',
'category_id' => 'required'
]);
// dd($request->all());
//exit;
$featured = $request->feature;
$featured_new_name=time().$featured->getClientOrignalName();
$featured->move('uploads/posts',$featured_new_name);
$post = Post::create([
'title'=>$request->title,
'content'=>$request->content,
'feature'=>'uploads/posts/'. $featured_new_name,
'category_id'=>$request->category_id
]);
Session::flash('success','Post Created Successfully.');
}
You should use file() method for retrieve file information from request. Try this code,
public function store(Request $request) {
$this->validate($request,[
'title' => 'required|max:255',
'content' => 'required',
'feature' => 'required|image',
'category_id' => 'required'
]);
// use file() method for retrive file data
$featured = $request->file('feature');
$featured_new_name = time() . $featured->getClientOrignalName();
$featured->move('uploads/posts', $featured_new_name);
$post = Post::create([
'title'=>$request->title,
'content'=>$request->content,
'feature'=>'uploads/posts/'. $featured_new_name,
'category_id'=>$request->category_id
]);
Session::flash('success','Post Created Successfully.');
}
I'm trying to implement one of Laravel's new features "Custom Validation Rules" and I'm running into the following error:
Object of class Illuminate\Validation\Validator could not be converted to string
I'm following the steps in this video:
New in Laravel 5.5: Project: Custom validation rule classes (10/14)
It's an attempt Mailgun API's Email Validation tool.
Simple form that requests: first name, last name, company, email and message
Here is my code:
web.php
Route::post('contact', 'StaticPageController#postContact');
StaticPageController.php
use Validator;
use App\Http\Validation\ValidEmail as ValidEmail;
public function postContact(Request $request) {
return Validator::make($request->all(), [
'firstname' => 'required|max:90',
'lastname' => 'required|max:120',
'company' => 'max:120',
'email' => [
'required', 'string', 'max:255',
new ValidEmail(new \GuzzleHttp\Client)
],
'message' => 'required',
]);
}
ValidEmail.php
<?php
namespace App\Http\Validation;
use Illuminate\Contracts\Validation\Rule;
use GuzzleHttp\Exception\GuzzleException;
use GuzzleHttp\Client as Guzzle;
class ValidEmail implements Rule
{
protected $client;
protected $message = 'Sorry, invalid email address.';
public function __construct(Guzzle $client)
{
$this->client = $client;
}
public function passes($attribute, $value)
{
$response = $this->getMailgunResponse($value);
}
public function message()
{
return $this->message;
}
protected function getMailgunResponse($address)
{
$request = $this->client->request('GET', 'https://api.mailgun.net/v3/address/validate', [
'query' => [
'api_key' => env('MAILGUN_KEY'),
'address' => $address
]
]);
dd(json_decode($request->getBody()));
}
}
Expectation
I'm expecting to see something like this:
{
+"address": "test#e2.com"
+"did_you_mean": null
+"is_disposable_address": false
+"is_role_address": false
+"is_valid": false
+"parts": {
...
}
}
Any help is much appreciated. I've been trying to get this simple example to work for over two hours now. Hopefully someone with my experience can help!
In your controller
Try this:
$validator = Validator::make($request->all(), [
'firstname' => 'required|max:90',
'lastname' => 'required|max:120',
'company' => 'max:120',
'email' => [
'required', 'string', 'max:255',
new ValidEmail(new \GuzzleHttp\Client)
],
'message' => 'required',
]);
if ($validator->fails()) {
return redirect()->back()
->withErrors($validator)
->withInput();
}
// if valid ...
According to your route, the postContact method is the method to handle the route. That means the return value of this method should be the response you want to see.
You are returning a Validator object, and then Laravel is attempting to convert that to a string for the response. Validator objects cannot be converted to strings.
You need to do the validation, and then return the correct response based on that validation. You can read more about manual validators in the documenation here.
In short, you need something like this:
public function postContact(Request $request) {
$validator = Validator::make($request->all(), [
'firstname' => 'required|max:90',
'lastname' => 'required|max:120',
'company' => 'max:120',
'email' => [
'required', 'string', 'max:255',
new ValidEmail(new \GuzzleHttp\Client)
],
'message' => 'required',
]);
// do your validation
if ($validator->fails()) {
// return your response for failed validation
}
// return your response on successful validation
}
I need to do validation in one of my controllers — I can't use a request class for this particular issue — so I'm trying to figure out how to define custom validation messages in the controller. I've looked all over and can't find anything that suggests it's possible. Is it possible? How would I do it?
public function store(Request $request)
{
$this->validate($request, [
'title' => 'required|unique:posts|max:255',
'body' => 'required',
]);
// Can I create custom error messages for each input down here? Like...
$this->validate($errors, [
'title' => 'Please enter a title',
'body' => 'Please enter some text',
]);
}
You should have a request class like below. message overwrite is what you are looking for.
class RegisterRequest extends Request
{
public function authorize()
{
return true;
}
public function rules()
{
return [
'UserName' => 'required|min:5|max:50',
'Password' => 'required|confirmed|min:5|max:100',
];
}
public function response(array $errors){
return \Redirect::back()->withErrors($errors)->withInput();
}
//This is what you are looking for
public function messages () {
return [
'FirstName' => 'Only alphabets allowed in First Name',
];
}
}
This did it
$this->validate($request, [
'title' => 'required',
'body' => 'required',
], [
'title.required' => 'Please enter a title',
'body.required' => 'Please enter some text',
]);