Laravel 5 : Couldn't instancing a model using tinker - laravel

I'm very new to laravel and PHP MVC frameworks, it's my first use of Eloquent. I'm trying to following a video tutorial.
So after creating a table by making new migration and migrate with artisan.
I created a model.Then I tried to instance it using tinker tool like so :
>>> $task = new App\Task;
I got this error :
=> App\Task {#672}
this my model class :
class Task extends Model
{
protected $table = 'tasks';
}
I did many research before asking this question, some people recommends using homestead, but I want to understand what I'm doing wrong.

This is not an error. It shows that an Object of App\Task Class has been created.
Now you can assign values to this $task Object. Like we have a field 'name' in tasks table then the following part of code can save the $task in database with value of 'name' field.
$task = new App\Task;
$task->name = 'My first task';
$task->save();

Related

Laravel 5 string as primary key

I'm working on a project that uses Laravel 5.5 and one of the models has its ID defined by the user. Below the model, setting $incrementing to false and having it in the $fillable array.
class AIOpportunity extends Model
{
protected $table = 'ai_opportunity';
protected $primaryKey = 'id_opportunity';
public $incrementing = false;
protected $fillable = [
'id_opportunity',
'budget',
'created_by'
];
}
The problem: when trying to execute this query :
$rec = AIOpportunity::where('id_opportunity', 'abc')->first();
It executed the following query in the database:
select * from ai_opportunity where id_opportunity=abc
Which throws an error because of the type. Is there something else I can do so Eloquent understands it's a varchar field?
I found the issue. It was not a Laravel problem, the settings in my question are OK. The problem was in the database I had locally. Although the table existed and it looked all right when I accessed via PhPMyAdmin I could see it there but also there were error messages saying that the table didn't exist.
Yes, pretty weird. I just deleted the local database and restored a backup from production. it works. The problem was in the database itself, not the Laravel App.

insert data to a migration without a model

How to insert data to a migration (table) without a model in Laravel, a migration with its model in which I define the corresponding relationships and the other only the migration
It can clearly be done according to the documentation of Laravel when you have the migration with your respective model, as follows.
$comment = new App\Comment(['message' => 'A new comment.']);
$post = App\Post::find(1);
$post->comments()->save($comment);
or
$post = App\Post::find(1);
$comment = $post->comments()->create([
'message' => 'A new comment.',
]);
This works for me only when I have with their respective models but not as I want to do
I am pending if someone can clarify with this
You can interact with database directly without a model using the DB facade:
DB::table('tablename')->insert(['column'=>'value']);
Same way you can use wheres, selects. For more details see Laravel docs - Database: Query Builder - Inserts

Can you create a new Model instance without saving it to the database

I want to create a whole bunch of instances of a model object in Laravel, then pick the optimal instance and save it to the database. I know that I can create an instance with Model::create([]), but that saves to the database. If possible I'd like to create a bunch of models, then only "create" the one that is best.
Is this possible?
I am using Laravel 5.0
You create a new model simply by instantiating it:
$model = new Model;
You can then save it to the database at a later stage:
$model->save();
You can create instances with Model::make(). It works the same way as create but it doesn't save it.
Whether or not this is best practice is another matter entirely.
Yes, it is possible different ways: you can use the mass assignment without saving.
Please remember to set first the $fillable property in your model.
WAY #1: using the method fill
$model = new YourModel;
$model->fill([
'field' => 'value',
'another_field' => 'another_value'
]);
$model->save();
WAY #2: using the constructor
$model = new YourModel([
'field' => 'value',
'another_field' => 'another_value'
]);
$model->save();
In YourModel set the $fillable property with the fileds allowed for mass assignment:
class YourModel extends Model
{
protected $fillable = ['field', 'another_field'];
// ...
}
Laravel documentation: https://laravel.com/docs/9.x/eloquent#mass-assignment
there is also a method you can call it statically to get new instance:
$modelInstance = $modelName::newModelInstance();
it takes array $attributes = [] as a parameter

Laravel model all() function is not working as intended

I have a model
namespace App;
use Illuminate\Database\Eloquent\Model;
class Contact extends Model {
protected $table = 'contacts';
//
}
And in the controller action
$c= Contact::all();
I am getting the "Whoops, looks like something went wrong." error.
Error detail:
FatalErrorException in ContactController.php line 9:
Class 'App\Http\Controllers\Contact' not found
The table "contacts" exists in the database.
What thing I am missing? Whats wrong here?
Tell your controller where your model is if it is in route of your project then on the top of your controller add
use App\Contact;
Or you may also define it every time
$c = App\Contact::all();
also in your model no need to define a table until it is not different from the plural model name. If your model name is Contact, laravel on its own query contacts table, you should define the table name if the model name is Contact and the table name is somethingElse.
Don't use
$c= Contact::all();
Instead use
$c = \App\Contact::all()
or
$c = new \App\Contact;
$c->all();
This is all that you have to use.
UPDATE: Just after digging in the concepts of OOP, I found this:
<?php
use \App\Contact;
var_dump(Contact::all());

Laravel 4 : Can't add new element in a database

I am new in Laravel 4 framework, I am working on library management project. I get all the data from my DB but I can't add a new book to my database.
I've created a form to add new books to my database. I get the Input::get('element') value from my store() method but the create Methode doesn't work . here's my code to save a new book :
Livre::create(array('titre' => Input::get('titre'),
'resume'=> Input::get('resume') ));
and here's my Model :
class Livre extends Eloquent {
protected $table = 'livre';
}
You need to create a new Model instance by calling:
$livre = new Livre;
Then add your 'fields':
$livre->titre = Input::get('titre');
$livre->resume = Input::get('resume');
Then save your new book by calling the save() or push() method:
$livre->save();
Or if you'd like to save a model with its relationships, use the push() method:
$livre->push();
Seems that when you say that create method doesn't work you mean that the record in your DB is created, but it has empty values. This happens when you dont't specify the fields enabled for massive assignment.
By default , the Eloquent model has the guarded attribute set to a wildcard blocking of mass assignment. To use the code that you showed us, modify your model :
class Livre extends Eloquent {
protected $table = 'livre';
protected $fillable = array(
'titre',
'resume'
);
}
You can read more here : Mass Assignment

Resources