in my app I want to attach a logged in user id to a post, below is my controller :
public function storejournal(JournalRequest $request) {
$input = $request->all();
//Input PDF
if ($request->hasFile('file')) {
$input['file'] = $this->uploadPDF($request);
}
//Insert data jurnal
$id = $request->id;
$journal = Edition::findOrFail($id)->journal()->create($input);
$journal->user_id = Auth::id();
$journal->user()->attach($request->input('penulis'));
return redirect()->route('edition', ['id' => $id]);
}
I tried the above controller it gave error : SQLSTATE[HY000]: General error: 1364 Field 'user_id' doesn't have a default value (SQL: insert intojournal(title,abstract,file,id_edition,journalslug,updated_at,created_at) values (Rancang bangun website Jurnal Online jurusan Teknik Informatika Universitas Palangkaraya, ddd, test3.pdf, 1, rancang-bangun-website-jurnal-online-jurusan-teknik-informatika-universitas-palangkaraya, 2016-11-15 03:43:34, 2016-11-15 03:43:34))
I don't understand what I did wrong, if someone can help that would be great. Thanks.
You're trying to create a Journal without specifying the user_id when it's created.
I'd suggest the following:
public function storejournal(JournalRequest $request) {
$input = $request->all();
//Input PDF
if ($request->hasFile('file')) {
$input['file'] = $this->uploadPDF($request);
}
//Insert data jurnal
$id = $request->id;
$journal = Edition::findOrFail($id)->journal()->create($input + ['user_id' => Auth::id()]);
$journal->user()->attach($request->input('penulis'));
return redirect()->route('edition', ['id' => $id]);
}
Also, don't forget to have user_id set as mass assignable in the Journal class.
The error says you should pass user_id too. You can do this with adding user ID to an $input:
$input = $request->all();
$input['user_id'] = auth()->user()->id;
Related
I want create tag for posts . I don't want tags repetitions to be saved,But it is stored repeated
public function store(Request $request)
{
$data = $request->all();
$post = Post::create($data);
if ($post && $post instanceof Post) {
$tags = $request->input('tags');
foreach ($tags as $tag){
$newTag = Tag::create(['name'=>$tag]);
$tags[] = $newTag->id;
}
$post->tags()->sync($tags);
return redirect()->back();
}
}
How can it be done?
updateOrCreate method will help check
It will create data if it not exists and update in case it already in db
Tag::updateOrCreate(['name'=>$tag]);
I'm studing Laravel CRUD.
Laravel Framework is 6.18.15
I would like to select of a record and update.
This is photo gallery.
Now if I click one of photo I can get below URL
https://mywebsite.net/public/edit?id=59
but in edit.blade.php I got this error
Undefined variable: id
Could someone teach me correct code please?
These are current code
Controller UPDATED
public function edit(Request $request)
{
$images = ImageGallery::find($id);
return view('edit',compact('images'));
}
public function editpcs(Request $request)
{
$this->validate($request, [
'title' => 'required',
'image' => 'required|mimes:jpeg,jpg'
]);
$input['image'] = time().'.'.$request->image->getClientOriginalExtension();
if($request->hasFile('image')) {
$image = $request->file('image');
$filename = time().'.'.$request->image->getClientOriginalExtension();
$image_resize = Image::make($image->getRealPath());
$image_resize->resize(1280, null, function ($image) {$image->aspectRatio();});
$image_resize->save(public_path('images/ServiceImages/' .$filename));
}
$request->image->move(public_path('images'), $input['image']);
$input['title'] = $request->title;
// ImageGallery::update($input);
$update = DB::table('image_gallery')->where('id', $id)->update( [ 'title' => $request->title, 'image' => $request->image]);
return view('edit',compact('images'))->with('sucess','sucessfully updated');
}
web.php
//edit view
Route::get('edit', 'ImageGalleryController#edit');
Route::post('edit', 'ImageGalleryController#edit');
//edit procces
Route::get('editpcs', 'ImageGalleryController#editpcs');
Route::post('editpcs', 'ImageGalleryController#editpcs');
UPDATE
#if($images->count())
#foreach($images as $image)
<div class='text-center'>
<small class='text-muted'>{{$image['id']}}/ {{$image['title']}} </small>
</div>
#endforeach
#endif
MODEL
namespace App;
use Illuminate\Database\Eloquent\Model;
class ImageGallery extends Model
{
protected $table = 'image_gallery';
protected $fillable = ['title', 'image'];
}
Actually $id is really undefined here, it would be $request->route('id') or request('id') or $_GET['id'] or $request->input('id') :
public function edit(Request $request)
{
$id = request('id');
$images = ImageGallery::findOrFail($id); // use findOrFail() id not exist in table, it throw a 404 error
return view('edit',compact('images'));
}
Take a look at the $_GET and $_REQUEST superglobals. Something like the following would work for your example:
$id = $_GET['id'];
$country = $_GET['country'];
In laravel you can to use Input::get(), But Input::get is deprecated in newer version of laravel, prefer the $request->input instead of Input::get :
$id= $request->input('id');
$country= $request->input('country');
It looks to me like this function:
public function edit(Request $request)
{
$images = ImageGallery::find($id);
return view('edit',compact('images'));
}
Should be something like this perhaps?
public function edit(Request $request)
{
$id = $request->input('id', null);
$images = ImageGallery::find($id);
return view('edit',compact('images'));
}
As it is, $id appears to be undefined before you attempt to pass it into the find() method. But according to your URL it is in the $request object. So you need to get it from there and into the function. You can read about this method in the docs.
public function edit(Request $request)
{
$id = request('id');
$images = ImageGallery::where('id',$id)->first();
return view('edit',compact('images'));
}
For adding to cart customer has to logg in,in cart table I have a column for user_id but in user_id column all of user_id in database add!for example for product1 all user1,user2,user3 ides add not just the one logged in
cart table:
Schema::create('cart', function (Blueprint $table) {
$table->increments('id');
$table->integer('product_id');
$table->char('user_id');
$table->string('session_id');
$table->string('product_name');
$table->string('user_email');
$table->integer('qty');
$table->integer('product_price');
$table->timestamps();
});
addToCart method in controller:
public function addtocart(Request $request){
$data = $request->all();
if (empty($data['user_email'])){
$data['user_email'] = ' ';
}
$user_id = User::get('id');
if (empty($user_id)){
$user_id = Auth::user()->id;
}
$session_id = Session::get('session_id');
if (empty($session_id)){
$session_id = Str::random(40);
Session::put('session_id' , $session_id);
}
DB::table('cart')->insert(['product_id' => $data['product_id'] , 'product_name' => $data['product_name'], 'user_id'=>$user_id,
'product_price' => $data['product_price'], 'qty' => $data['qty'], 'user_email' => $data['user_email'] , 'session_id' => $session_id ]);
return redirect('cart');
}
what is the problem?
You are currently requesting all the user ids by doing $user_id = User::get('id'); so if you want to set user_id as your authenticated user id you need to replace:
$user_id = User::get('id');
if (empty($user_id)){
$user_id = Auth::user()->id;
}
by:
$user_id = Auth::user()->id;
or shorter version:
$user_id = Auth::id();
I have the following rule so far.
$rules['name'] = [
'required',
'string',
'min:3',
'max:255',
Rule::unique('user_templates', 'name')->ignore($this->id),
];
Users can create records, but all his records must have a unique name (other users can have records with the same name). How can I do this? Also, $this->id on update is always null. What am I doing wrong?
Controller
public function update(UserTemplatesRequest $request, $slug)
{
try {
$model = UserTemplates::where('slug', XSS::clean($slug))
->firstOrFail();
} catch (ModelNotFoundException $err) {
return redirect()->action('UserTemplatesController#index');
}
$data = $request->validated();
if ($model->updateTemplate(XSS::clean($data, ['file']), $request)) {
$message = "There was an error, please try again";
$action = 'index';
$id = '';
} else {
$message = "Category Updated";
$action = 'edit';
$id = $model->id;
}
return redirect()->action("CategoriesController#{$action}", [$id])
->with('message', $message);
}
According to your Rule you can try and use a where clause to narrow it down to one user and not whole project like:
Rule::unique('user_templates', 'name')->where(function (Builder $query) {
return $query->where(
'user_id', '=', $this->user()->id;
})
user_id is the column inside your user_templates table that works as a foreign key with your users table.
About $this->id it should be $this->user()->id to retrieve your user id
I have an update post form, where I need to update the name of the post in posts table and the associated text within the text table. I can't seem to get it to work at all.
Model - Post.php
public function text()
{
return $this->hasOne('Text');
}
Model - Text.php
public function post()
{
return $this->belongsTo('Post');
}
Controller - PostController.php
public function updateQuestionForm($id)
{
$post = Post::find($id);
$input = Input::all();
$rules = array(
'text' => 'required',
);
$validation = Validator::make($input, $rules);
if ($validation->fails()) {
return Redirect::back()->withErrors($validation)->withInput();
} else {
$post->title = Input::get('title');
$post->save();
$text = $post->text();
$text->text = Input::get('text');
$post->text()->save($text);
$message = "Post updated";
return Redirect::to('question/'.$post->id.'/'.$post->slug.'/')->with('message', $message);
}
}