How to pass array in db using laravel 7 - php

I'm trying array data send in db but I got error
here is my function where i send data in db
public function create(Request $request)
{
$tags = explode(",", $request->labels);
$posts = new Post();
$posts->user_id = $request->id;
$posts->title = $request->title;
$posts->description = $request->description;
$tags = explode(",", $request->labels);
$posts->tags = $tags; // error is here in this line
$posts->save();
return redirect()->back()->with('message' , 'post created!!!!!');
}

If $posts->tags is related - i.e Post hasMany Tag, Tag belongsToMany Post - then you should be able to attach the tags to the post like so:
$posts->tags()->attach($tags);
$posts->save();

Related

An Update in Laravel Framework is returning A new Record

I am new to PHP and Laravel. I have learned much, but I am having a problem seeing my error in what should be a simple task.
I have a form which is populated from data in a MySQL database. When I submit it, it creates a new record instead of updating the existing record. This is the form action that I am using:
<form action="{{route('updateAlert', $alert->id)}}" method="post" name="saveAlert" id="saveAlert" class="needs-validation"
#csrf
#method("PUT")
///form fields here
</form>
Here are the two related routes. editAlert brings you to the form above. updateAlert is supposed to bring you to the update method on my AlertController.
Route::get('/alerts/edit/{id}', 'AlertController#edit')->name('editAlert');
Route::put('/alerts/edit/{id}', 'AlertController#update')->name('updateAlert');
Here is what my AlertController looks like:
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function update(Request $request, Alert $alert)
{
$alert->type = $request->type;
$alert->title = $request->title;
$alert->body = $request->body;
$alert->link = $request->link;
$alert->eff_dt = Carbon::parse($request->eff_dt);
$alert->exp_dt = Carbon::parse($request->exp_dt);
$alert->note = $request->note;
$alert->user_id = auth()->user()->id;
$alert->save();
return redirect()->route('viewAlerts')->with('success', 'Your alert has been updated.');
}
What am I missing? I have the same basic code in another section of the app that is working as expected. Thanks in advance.
You Are Not Fetching your row id. You need to use model and pass your id to your model to update any specific row.
Ex.
I the model name just pass your model name.
public function update(Request $request, Alert $alert)
{
$alert = ModelName::find($alert);
$alert->type = $request->type;
$alert->title = $request->title;
$alert->body = $request->body;
$alert->link = $request->link;
$alert->eff_dt = Carbon::parse($request->eff_dt);
$alert->exp_dt = Carbon::parse($request->exp_dt);
$alert->note = $request->note;
$alert->user_id = auth()->user()->id;
$alert->save();
return redirect()->route('viewAlerts')->with('success', 'Your alert has been updated.');
}
To update things in Laravel, you need a query builder object; Alert $alert returns an object of the model, so it can not be used to update things.
Note: find method is a special method whose objects can be used to update records, unlike the "first" method.
So your code must be changed to:
public function update(Request $request, Alert $alert)
{
$alert = Alert::where('id', $alert->id); // or: Alert::find($alert->id);
$alert->type = $request->type;
$alert->title = $request->title;
$alert->body = $request->body;
$alert->link = $request->link;
$alert->eff_dt = Carbon::parse($request->eff_dt);
$alert->exp_dt = Carbon::parse($request->exp_dt);
$alert->note = $request->note;
$alert->user_id = auth()->user()->id;
$alert->save();
}

Laravel Model not returning properties with default value after creation

In my controller after I create a new Post I return the new post in a post variable. For some reason I don't get the properties with default values back. I noticed that if I set the value to something in controller it does indeed return the properties in the payload.
public function create(Request $request)
{
$validatedData = $request->validate(PostValidator::$create);
$post = new Post();
$post->postcategory_id = $request->input('postcategoryid');
$post->user_id = $request->input('authorid');
$post->thumbnail = $this->uploadFile($request, 'thumbnail', config('app.defaultImage'));
$post->video = $request->input('video');
$post->slug = $this->slugify($request->input('title'));
$post->url = '/publicaciones/'.$this->slugify($request->input('title'));
$post->title = $request->input('title');
$post->body = $request->input('body');
$post->isVisible = false; //IF I DO THIS isVisible is returned in $post variable
$post->save();
$post->load(['postcategory','author']);
return response()->json([
'post' => $post,
]);
}
you can say laravel works like that. default values defined in the database layer is absent in a newly created object. however you can use refresh to refresh the object before returning. and it will have the missing values then.
$post = new Post();
$post->attribute = $request->attribute;
$post->save();
$post = $post->refresh();
return $post;
or you can set default values in the model layer
protected $attributes = [
'isVisible' => false
];
and you will have the default values when returning a newly created object.

Passing posts view id to another controller so I can access table records in Laravel

So I got posts page, where I have my post. The post has ID which leads to posts table. For it I have PostsController where everything is accessible thru $post->id, $post->name etc.
But I have another table named orders and on submit button, it needs some of the information from posts table by id.
I have post with url posts/{id} and there's submit button in the view
The button needs to get $post information to OrdersController with submit information.
I've tried this in OrdersController
public function store(Request $request)
{
$this->validate($request, [
]);
$post = Post::all();
$order = new Order;
$order->client = Auth::user()->name;
$order->phone = Auth::user()->phone;
$order->vehicle = $post->id;
$order->date_from = $request->input('date_from');
$order->save();
return redirect('/posts')->with('success', 'Rezervēts');
}
$posts = Post::all(); is getting all array information from table but cannot use specific id.
And I have this in PostsController
public function show($id)
{
$post = Post::find($id);
$images = Image::All();
return view('posts.show')->with(compact('post', 'images'));
}
Route for show function
Error that I'm getting with shown code: Property [id] does not exist on this collection instance.
Expected results:
orders table
Error: Property [id] does not exist on this collection instance.
Problem: Can't get exact id from view to another controller, so I can access posts table records that I need from OrdersController.
Ps. I've been thru most of the pages on this error, but can't seem to find the one that would help.
I would modify the route so that the affected post.
Route:
Route::post('/order/{post}/store', 'OrderController#store')->name('order.store');
Controller (store method):
public function store(Post $post, Request $request){
$this->validate($request, [
]);
$order = new Order;
$order->client = Auth::user()->name;
$order->phone = Auth::user()->phone;
$order->vehicle = $post->id;
$order->date_from = $request->input('date_from');
$order->save();
return redirect('/posts')->with('success', 'Rezervēts');
}
Okay, thanks.
Solved: {{ Form::hidden('id', $post->id) }} in view.
Controller: $post = Post::findorfail($request->id);
Then: $post->(whatever you need from table)

how to save data in two different tables of database using single form in laravel 5.2

my controller here two tables name storeData and 2nd is dataFile.
public function storeData(Requests $request){
$data= new Data;
$data->name = $request->input('name');
$data->description = $request->input('description');
$data->save();
$datafile= new Datafile;
$datafile->data_id = $request->input('data_id');
$datafile->dataname= $request->input('$dataname');
$datafile->save();
return back;
}

Laravel:: reuse article id into new table

I need to be able to make a "like" system. I have three tables. Users, Articles, Likes.
In the Articles table I have the id, title, body. In Likes I have id, user_id, and article_id.
So when a person presses like on the article I fill the table with their user id and the article_id.
However I'm running into the problem of adding the id. This is basic to most I know, I have seen the laravel videos but its still new to me.
Here is what I have in the article controller.
$article = new Article();
$article->body = 'new article body';
$article->title = 'new article Title';
$article->type = 'fashion';
$article->save();
$articles = Article::where('type', 'fashion')->get();
//$articles = Article::all();
return view('articles.index', compact('articles'));
public function store()
{
$request = Request::all();
$likes = new like();
$likes ->article_id = Article::find($id);
$likes->user_id = Auth::user()->id;
$name = Auth::user()->name;
$likes->save();
$followers = new Follower();
$followers->follower_id = Auth::user()->id;
$followers->user_id = $request['user_id'];
$name = Auth::user()->name;
$followers->save();
return redirect('article');
}
You are trying to use a variable which doesn't exist. Variable $id being used on this line
$likes ->article_id = Article::find($id);
is not initialized anywhere. Maybe you are expecting it to be on the Request? So in that case, $request->id in that case.
Also if your model is called Like than you should fix the case on this line $likes = new like(); to $likes = new Like();.

Categories