Create Join Between Tables Laravel - laravel

I Have 2 tables : Posts - Comment
I Want to Make Relation Between These 2 Tables and Need to Update The Comment That Has "1" Post_ID :
Route:
Route::get('join', 'JoinController#Join');
Controller :
public function Join()
{
$Comment = Posts::find(1)->Comment;
$Comment->Title = "JOIN";
$Comment->save();
}
Posts Model :
public function Comment()
{
return $this->hasOne('App\Comment');
}
Comment Model :
public function Posts()
{
return $this->belongsTo('App\Posts');
}
but i recieve this error :
Trying to get property of non-object

Do this instead:
$comment = new Comment;
$comment->Title = 'JOIN';
#comment->post_id = 1;
$comment->save();
Or you can use create() method:
$Comment = Posts::find(1)->Comment()->create(['Title' => 'JOIN']);
If you'll use create() method, make sure Title is in the $fillable array.

$Comment = Posts::find(1)->Comment()->first();
$Comment->Title = "JOIN";
$Comment->save();

Related

why i can't call name from table food?

public function orderlist(Request $request){
$id = $request->id;
$data['order'] = Order::where('shop_id',$id)->orderBy('id')->get();
foreach($data['order'] as $orders){
$orders->shop = Shop::where('id',$orders->shop_id)->first();
$orders->food = Food::where('id',$orders->food_id)->get();
}
return $orders->food->name;
return view ('administrator.users.list_order.index',$data);
}
If you set up proper Eloquent relationships, this code could be rewritten like so:
public function orderlist(Request $request, Shop $shop){
$orders = $shop->orders()->with(['food'])->get();
return view ('administrator.users.list_order.index',compact('orders'));
}
Check out the docs here: https://laravel.com/docs/5.7/eloquent-relationships

laravel 5.7 how to pass request of controller to model and save

I am trying to pass $request from a function in controller to a function in model.
THis is my controller function:
PostController.php
public function store(Request $request, post $post)
{
$post->title = $request->title;
$post->description = $request->description;
$post->save();
return redirect(route('post.index'));
}
how save data in model Post.php?
I want the controller to only be in the role of sending information. Information is sent to the model. All calculations and storage are performed in the model
Thanks
You can make it even easier. Laravel has it's own helper "request()", which can be called anywhere in your code.
So, generally, you can do this:
PostController.php
public function store()
{
$post_model = new Post;
// for queries it's better to use transactions to handle errors
\DB::beginTransaction();
try {
$post_model->postStore();
\DB::commit(); // if there was no errors, your query will be executed
} catch (\Exception $e) {
\DB::rollback(); // either it won't execute any statements and rollback your database to previous state
abort(500);
}
// you don't need any if statements anymore. If you're here, it means all data has been saved successfully
return redirect(route('post.index'));
}
Post.php
public function postStore()
{
$request = request(); //save helper result to variable, so it can be reused
$this->title = $request->title;
$this->description = $request->description;
$this->save();
}
I'll show you full best practice example for update and create:
web.php
Route::post('store/post/{post?}', 'PostController#post')->name('post.store');
yourform.blade.php - can be used for update and create
<form action='{{ route('post.store', ['post' => $post->id ?? null]))'>
<!-- some inputs here -->
<!-- some inputs here -->
</form>
PostController.php
public function update(Post $post) {
// $post - if you sent null, in this variable will be 'new Post' result
// either laravel will try to find id you provided in your view, like Post::findOrFail(1). Of course, if it can't, it'll abort(404)
// then you can call your method postStore and it'll update or create for your new post.
// anyway, I'd recommend you to do next
\DB::beginTransaction();
try {
$post->fill(request()->all())->save();
\DB::commit();
} catch (\Exception $e) {
\DB::rollback();
abort(500);
}
return redirect(route('post.index'));
}
Based on description, not sure what you want exactly but assuming you want a clean controller and model . Here is one way
Model - Post
class Post {
$fillable = array(
'title', 'description'
);
}
PostController
class PostController extend Controller {
// store function normally don't get Casted Objects as `Post`
function store(\Request $request) {
$parameters = $request->all(); // get all your request data as an array
$post = \Post::create($parameters); // create method expect an array of fields mentioned in $fillable and returns a save dinstance
// OR
$post = new \Post();
$post->fill($parameters);
}
}
I hope it helps
You need to create new model simply by instantiating it:
$post = new Post; //Post is your model
then put content in record
$post->title = $request->title;
$post->description = $request->description;
and finally save it to db later:
$post->save();
To save all data in model using create method.You need to setup Mass Assignments when using create and set columns in fillable property in model.
protected $fillable = [ 'title', 'description' ];
and then call this with input
$post = Post::create([ 'parametername' => 'parametervalue' ]);
and if request has unwanted entries like token then us except on request before passing.
$post = Post::create([ $request->except(['_token']) ]);
Hope this helps.
I find to answer my question :
pass $request to my_method in model Post.php :
PostController.php:
public function store(Request $request)
{
$post_model = new Post;
$saved = $post_model->postStore($request);
//$saved = response of my_method in model
if($saved){
return redirect(route('post.index'));
}
}
and save data in the model :
Post.php
we can return instance or boolean to the controller .
I returned bool (save method response) to controller :
public function postStore($request)
{
$this->title = $request->title;
$this->description = $request->description;
$saved = $this->save();
//save method response bool
return $saved;
}
in this way, all calculations and storage are performed in the model (best way to save data in MVC)
public function store(Request $request)
{
$book = new Song();
$book->title = $request['title'];
$book->artist = $request['artist'];
$book->rating = $request['rating'];
$book->album_id = $request['album_id'];
$result= $book->save();
}

Laravel and algolia, ignore array if null

I have this code:
public function toSearchableArray()
{
$data = $this->toArray();
$data['_geoloc'] = $this->_geoloc->toArray();
$data['address'] = $this->address->toArray();
return $data;
}
However sometimes $data['entities'] is null therefore throwing me an error:
[Symfony\Component\Debug\Exception\FatalThrowableError]
Call to a member function toArray() on null
Is there any way to by-pass that?
You need to check elements if they exist and not null before call methods on them, like this:
public function toSearchableArray()
{
$data = $this->toArray();
$data['_geoloc'] = !empty($this->_geoloc) ? $this->_geoloc->toArray() : null;
$data['address'] = !empty($this->address) ? $this->address->toArray() : '';
return $data;
}
Also $this->toArray(); will convert the model instance to an array with all relations. So you need to load them like: $this->load('_geoloc', 'address'); and call only $data = $this->toArray();
I assume address is a relation to another table.
toArray() will convert it, if it was loaded before
public function toSearchableArray()
{
$this->address;
$data = $this->toArray();
return $data;
}
Is _geoloc also a relation to another table?
I think you can try this:
public function toSearchableArray()
{
$data = $this->toArray();
$data['_geoloc'] = $this->_geoloc->toArray();
$data['address'] = $this->address->toArray();
print('<pre style="color:red;">');
print_r($data);
print('</pre>');
exit;
return $data;
}
Hope help for you !!!

Elequent Relationships Error

I have created a posts table & comments table for posts comments.
I want to get my posts with their comments ...
In my Post Model :
public function comments()
{
return $this->hasMany('App\Comment');
}
In my Comment Model :
public function post()
{
return $this->belongsTo('App\Post');
}
And this is my Controller :
public function show($ID)
{
try {
$post = Post::findOrFail($ID);
$comments = Post::find($ID)->comments;
$randomPosts = Post::all()->random(3);
return view('show', compact('post','comments','randomPosts'));
} catch (ModelNotFoundException $e) {
$posts = Post::orderBy('ID', 'DESC')->paginate(5);
return view('welcome', compact('posts'));
}
}
But I get this error :
Undefined property: Illuminate\Database\Eloquent\Collection::$ID
What is my problem ?
You need to assign the $ID variable to your id that you want to retrieve the post
For example let's say that you want the post with id 1 and its comment.
First you can retrieve the comments for first article like this:
$comments = App\Post::find(1)->comments;
foreach ($comments as $comment) {
echo $comment
}
Of course you can retrieve the post represents one comment.
For example the post that has the first comment:
$comment = App\Comment::find(1);
echo $comment->post->title;

Setting a table name in a model?

Im trying to pass in a table name to my model, as the model operates on two tables, but has the same methods.
I do it like so:
$this->model = new Emotions(array('section' => 'red'));
And in the model I set the table like:
public function __construct($attributes = array(), $exists = false){
parent::__construct($attributes, $exists);
$this->table = $attributes['section'];
}
But I get the error:
Undefined index: section
Any ideas where I'm going wrong?
Yes i get it, This class maybe running twice.
Please try this.
public function __construct($attributes = array(), $exists = false){
parent::__construct($attributes, $exists);
if(isset($attributes['section'])) {
$this->table = $attributes['section'];
}
}
My personal suggestion
<?php
class Emotions extends Eloquent
{
public function setTableName($name)
{
$this->table = $name;
return $this;
}
}
And you can use like this
$emotion = new Emotions(array('foo' => 'bar'))
->setTableName('blabla')
->save();
add below line to your class.
protected $fillable = array('section');
http://laravel.com/docs/eloquent#mass-assignment

Resources