From This answer I am trying to update department data. Code as below :
$id = Crypt::decrypt($id);
$rules = Department::$rules;
$rules['name'] = $rules['name'] . ',id,' . $id;
$rules['department_code'] = $rules['department_code'] . ',id,' . $id;
dump($rules);
$validator = Validator::make($data = $request->all(), $rules);
if ($validator->fails()) return Redirect::back()->withErrors($validator)->withInput();
$department = Department::findOrFail($id);
But the validator says :
The department code has already been taken.
The name has already been taken.
So whats wrong ?
My rules array is:
public static $rules = [
'name' => 'required|unique:departments|max:255',
'department_code' => 'required|unique:departments|max:127',
];
Change your $rules array as:
public static $rules = [
'name' => 'required|max:255|unique:departments',
'department_code' => 'required|max:127|unique:departments',
];
Then you can use it to append id in the rules.
Related
I have a big struggle about adding file uploading to an existing laravel 6 form.
I want to add the file url to database for future to be displayed (or downloaded).
When i try to do something nothing is happaning, nothing in DB nothing in file dir.
Here is my model:
protected $fillable = [
'age',
'last_rab',
'names',
'email',
'phone',
'last_pos',
'cv',
'msg',
'status'
];
Here is my Controller:
public function store(Request $request)
{
$request->validate([
'names' => 'required',
'age' => 'required',
'last_rab' => 'required',
'last_pos' => 'required',
'phone' => 'required',
'cv' => 'required|mimes:doc,docx,pdf,txt|max:2048',
'msg' => 'required'
]);
if ($request->captcha != 58) {
return redirect()->back()->withInput()->with('warning', 'Wrong');
}
$karieri = new Karieri;
$karieri->age = $request->age;
$karieri->last_rab = $request->last_rab;
$karieri->names = $request->names;
$karieri->email = $request->email;
$karieri->phone = $request->phone;
$karieri->last_pos = $request->last_pos;
if ($request->hasfile('cv')) {
$file = $request->file('cv');
$name = time().'.'.$file->extension();
$file->move(public_path() . '/storage/app/public', $name);
$data = $name;
$karieri->cv = json_encode($data);
}
$karieri->msg = $request->msg;
$karieri->status = 0;
$karieri->save();
return redirect()->back()->with('success', 'Thanks');
}
Can somebody say how to do this?
I want to upload image for my posts and have polymorphism relation one to one (because I have other tables and they need image too ) between posts and images
And when I want to send request and store the image in database , I get this error:
BadMethodCallException: Call to undefined method App\Models\Image::move()
I'm creating an API so :
My postman :
My relations :
Image model :
class Image extends Model
{
use HasFactory;
protected $fillable = [
'image'
];
public function imageable(){
return $this->morphTo();
}
}
Post model :
class Post extends Model
{
use HasFactory;
use \Conner\Tagging\Taggable;
protected $fillable = [
'user_id' ,
'category_id' ,
'title' ,
'body' ,
'study_time',
'likes',
'status',
'tags',
];
public function image(){
return $this->morphOne(Image::class , 'imageable');
}
}
And the PostController , store() method :
public function store(Request $request )
{
$data = $request->all();
$validator = Validator::make($data, [
'user_id'=>'required',
'category_id'=>'required',
'title' => 'required|max:150|unique:posts',
'body' => 'required',
'study_time'=>'required',
'tags'=>'nullable|string',
]);
if ($validator->fails()) {
return response()->json(['error' => $validator->errors(), 'error']);
}
//separate tags
$tags = explode(",", $request->tags);
$image = new Image;
$getImage = $request->file('image');
$imageName = time().'.'.$getImage->extension();
$image->move(public_path('images'), $imageName);
$post = Post::create($data);
$post->image()->save($image);
//save tags
$post->tag($tags);
return response()->json([
"success" => true,
"message" => "successfull",
"data" => $post
]);
}
Where is my mistake?
After a month of this challenge, I was finally able to solve it :}
To make the code better and cleaner, I added another column to my image table : path
it's for saving path of image , and another column : image
and i added the path to my fillable in Image model and i edited the code to this :
public function store(Request $request )
{
$data = $request->all();
$validator = Validator::make($data, [
'user_id'=>'required',
'category_id'=>'required',
'title' => 'required|max:150|unique:posts',
'body' => 'required',
'study_time'=>'required',
'tags'=>'nullable|string',
]);
if ($validator->fails()) {
return response()->json(['error' => $validator->errors(), 'error']);
}
//separate tags
$tags = explode(",", $request->tags);
$image = new Image;
$getImage = $request->image
$imageName = time().'.'.$getImage->extension();
$imagePath = public_path(). '/images/posts';
$image->path = $imagePath;
$image->image = $imageName;
$getImage->move($imagePath, $imageName);
$post = Post::create($data);
$post->image()->save($getImage);
$post->tag($tags);
return response()->json([
"success" => true,
"message" => "successfully",
"data" => $post
]);
}
I am sending base64 image along with some form data from postman to laravel 5 with mysql. The code works well and returns the success json as well. All values from json is stored in mysql but the json image path is not stored in database, instead some code is stored in databse.
My actual json response in postman is =>
{"success":{"userid":"4","fname":"s","lname":"s","img":"uploads\/5a3f6218a1ed0.jpg"}}
All above json values are stored in databse but the img json path is not stored, instead following data is stored in database.
/9j/4AAQSkZJRgABAQEAYABgAAD/2wBDAAoHBwgHBgoICAgLCgoLDhgQDg0NDh0VFhEYIx8lJCIfIiEmKzcvJik0KSEiMEExNDk7Pj4+JS5ESUM8SDc9Pjv/2wBDAQoLCw4NDhwQEBw7KCIoOzs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs
My Laravel API code is
public function add(Request $request)
{
$validator = Validator::make($request->all(), [
'userid' => 'required',
'fname' => 'required',
'lname' => 'required',
'img' => 'required',
]);
if ($validator->fails()) {
return response()->json(['error'=>$validator->errors()], 401);
}
$input = $request->all();
$user = News::create($input);
$success['userid'] = $user->userid;
$success['fname'] = $user->fname;
$success['lname'] = $user->lname;
if ($user->img)
{
$img2 = $user->img;
$img3 = str_replace('data:image/jpg;base64,', '', $img2);
$img3 = str_replace(' ', '+', $img3);
$data = base64_decode($img3);
$file = 'uploads/' . uniqid() . '.jpg';
file_put_contents($file, $data);
$imgfile = $file;
$success['img'] = $imgfile;
}
return response()->json(['success'=>$success], $this->successStatus);
}
What actually i am missing...
This is because you save record like this:
$user = News::create($input);
so you don't save $imgfile in database.
You can add after:
$success['img'] = $imgfile;
the following line to update record
$user->update(['img' => $imgfile]);
or you can change the order of your code to create News record later with valid img field already.
Also keep in mind you are using wrong variable names. There is no point to have $user variable that holds News model.
As Marcin has stated above it's because you're not saving imgfile into the database.
I would also consider refactoring some of your code so that the add method isn't so verbose. Consider something like the following code block. Please note no use statements have been used an no try/catch has been implemented.
I have also found that it is generally better to give fuller variable and property names. Such as fname I would call first_name/firstName depending on context.
<?php
class ApiController
{
/**
* Add news item
*
* #param Request $request
* #return \Illuminate\Http\JsonResponse
*/
public function add(Request $request)
{
$validator = $this->validateData($request);
if ($validator->fails()) {
return response()->json(['error'=>$validator->errors()], 422);
}
$news = News::create($request->all());
if ($news) {
$success['userid'] = $news->userid;
$success['fname'] = $news->fname;
$success['lname'] = $news->lname;
$success['img'] = $this->uploadImage($news);
$news->update(['img' => $success['img']]);
return response()->json(['success'=>$success], $this->successStatus);
}
return response()->json(['error'=>'An Error occurred when creating the news item'], 422);
}
/**
* Upload Image and return file name
*
* #param $news
* #return string
*/
protected function uploadImage($news)
{
$image = $news->img;
$image = str_replace('data:image/jpg;base64,', '', $image);
$image = str_replace(' ', '+', $image);
$data = base64_decode($image);
$file = 'uploads/' . uniqid() . '.jpg';
file_put_contents($file, $data);
return $file;
}
/**
* Validate inbound request
*
* #param $request
*/
protected function validateData($request)
{
Validator::make($request->all(), [
'userid' => 'required',
'fname' => 'required',
'lname' => 'required',
'img' => 'required',
]);
}
}
I am working with Laravel 4 validation right now. My basic setup is done and tested. I can fill the form in view and submit to controller. I can save all details to database using model. I am having a problem now with validation.
I use Input::get() to capture each of the posted variables in the controller. I read that validation should ideally be done in the model. where am I supposed to invoke the validator? Model or Controller? and how am I supposed to pass the validator the $input? is it an array of all variables posted or am I missing something?
Laravel 4 documentation really fails to illustrate with examples answers to common usage questions.
This is the validator I set up in my model:
public static function validate($input)
{
$rules = array(
# place-holder for validation rules
'firstname' => 'Required|Min:3|Max:40|Alpha',
'lastname' => 'Required|Min:3|Max:40|Alpha',
'email' => 'Required|Between:3,64|Email|Unique:users',
'country' => 'Required',
'password' =>'Required|AlphaNum|Between:7,15|Confirmed',
'password_confirmation'=>'Required|AlphaNum|Between:7,15'
);
# validation code
$validator = Validator::make($input, $rules);
/*if( $validator->passes() ) {
} else {
# code for validation failure
}*/
}
controller:
public function register()
{
/*Create new user if no user with entered email exists. Use validator to ensure all fields are completed*/
$user = new User;
/*Handle input in POST*/
$email = Input::get('email');
$password = Input::get('password');
$passwordConfirmed = Input::get('password_confirmation');
$firstName = Input::get('firstname');
$lastName = Input::get('lastname');
$country = Input::get('country');
$user->email = $email;
$user->password = Hash::make($password);
$user->firstname = $firstName;
$user->lastname = $lastName;
$user->country = $country;
//$user->save();
$this->layout->content = View::make('test');
}
and I've been following this link so far when it comes to validation. Please help as I am new to this framework
You are missing the input in the validator, you did not defined it
Use it like
$input = Input::all();
$validator = Validator::make($input, $rules);
or
$validator = Validator::make(Input::all(), $rules);
and take a look at the forums, this will help you more than that blog: http://forums.laravel.io/viewtopic.php?id=12104
I'm trying to save to a database, I wish to ignore the post if it's already in the database. This is how I currently save it. The postid has to be unique.
public function save($type, $postid, $url, $author, $content)
{
$post = new Post;
$post->type = $type;
$post->postid = $postid;
$post->url = $url;
$post->author = $author;
$post->content = $content;
echo $post;
$post->save();
}
Use the Validator class' unique validation rule on whatever fields you wish to be unique before trying to save.
$input = array('postid' => $postid);
$rules = array(
'postid' => 'unique:posts,postid'
);
$validate = Validator::make($input,$rules);
if($validator->passes())
{
$this->save($type, $postid, $url, $author, $content)
}
else
{
$messages = $validator->messages();
echo $messages->first('postid');
}
You can use Post::findOrFail(UNIQUE_ID) using it in a try ... catch ... structure to fallback if a post has already this unique ID you want to set.
You can check unique in validation. I'm not sure if you are checking unique primary postid. I would suggest you to keep postid as primary key & auto increment. You can match the post title for duplication.
$rules = array(
'postid' => 'required|unique:posts'
);
$validator = Validator::make(Input::all(), $rules);
if($validator->fails()){
return Redirect::back()->withInput()->with('errors', $validator->messages());
}else{
$data = array(
'type' => Input::get('type'),
'postid' => Input::get('postid'),
'url' => Input::get('url'),
'author' => Input::get('author'),
'content' => Input::get('content')
);
if(Post::create($data)){
Session::flash('messages', 'Post created.');
return Redirect::route('routename');
}
}