Class name problem on laravel 5.8 with Request->input - php

I'm trying to follow a tutorial to create a simple web scraper here using Laravel, but symfony threw a "Class name must be a valid object or string" error on line 49. In phpstorm it did gave me a light warning of field accessed with magic method on $website->title
I've tried to declare $title as a public var in my App/Website.php but it still gave me this error.
here's the snippet of the code with error
public function store(Request $request)
{
$this->validate($request,[
'title'=>'required',
'url'=>'required',
'logo'=>'required'
]);
$website = new Website();
$website->title = new $request->input('title');
$website->url = $request->input('url');
$website->logo = $this->uploadFile('logo', public_path('uploads/'), $request)["filename"];
$website->save();
return redirect()->route('websites.index');
}
/**
* Display the specified resource.
*
and here's my App/Website Class:
namespace App;
use Illuminate\Database\Eloquent\Model;
class Website extends Model
{
protected $table = "website";
public $title;
/**
* #var array|string|null
*/
public $url;
public $logo;
}
It should've saved the title, url and logo to a sql db i named scraper but it keeps throwing this error. Please help.
Edit 2: I apologize it seems i copied the code shown by symfony, my actual WebsiteController is like this copied wrong code again, here's the actual actual code:
public function store(Request $request)
{
$this->validate($request,[
'title'=>'required',
'url'=>'required',
'logo'=>'required'
]);
$website = new Website();
$website->title = new $request->input('title');
$website->url = $request->input('url');
$website->logo = $this->uploadFile('logo', public_path('uploads/'), $request)["filename"];
$website->save();
return redirect()->route('websites.index');
}

Here new should not be there ,$website->title = new $request->input('title'); , You are not making object from any class. i guess you miss type.
and you can still get your data by just $request->title; i prefer this because it short your code and still readable.
Do it like below
$website->title = $request->input('title');
Or
$website->title = $request->title;
and also for saving data into db you don't need to declare variable.
simply in model add protected $fillable=['title','url','logo'];
or if you using save() method you don't even need to add $fillable

Related

Import Model via Ajax Request Laravel - without namespacing the model

I am trying to import a model via an Ajax request without namespacing the model.
public function dataTypeRender(Request $request)
{
$input = request()->all();
$model = $request->input('model'); //this is the model name
$cols = $request->input('cols');
$modelTest = $model::all(); //not working
dd($modelTest);
}
Is there a way to do this? I'm trying to then do something with the model data.
I think without namespace it gonna be a little harder, because your model could be any model, but i think this could help you.
public function example(Request $request){
$data = $request->all(); //get All data request
$namespace = 'App\\'; //set namespace
$modelWithNameSpace = $namespace.$data['model']; //concat namespace and model name
$model = str_replace("'", "", $modelWithNameSpace); //remove quotes (idk if it's the best approach)
return $model::all(); //return the modell with all
}
This seemed to work nicely.
$model = 'App\\' . $request('model'); // adjust for the namespace/folder where you put your models
$data = (new $model)->all();
or
$data = (new $model)->find(1);

Laravel 5.6 database operations in model

I have a controller called UserController, in that controller i am inserting a row of data to table "user" like this
$user = new UsersModel();
$user->first_name = $request->input('firstName');
$user->last_name = $request->input('lastName');
$user->about = $request->input('userAbout');
$user->join_date = date('Y-m-d');
$user->save();
My Question is, can i write this in my model called UsersModel???
Something Like,
( The insertData($data) is called from controller class.)
class UsersModel extends Model
{
protected $fillable = ['id','first_name','last_name','about','image','join_date','created_at','updated_at'];
protected $table = 'users';
public function insertData($data) {
// nb: $data contains values of fileds
// insert operation
//also return some values
}
}
You don't need to define your own function when you can already do it through Eloquent by simply calling the static method create magically:
$ref = UsersModel::create([
'col' => 'val'
]);
where $ref contains the information about the created data.
No need to reinvent the wheel in this instance.
However, your own custom method is possible too, make sure your function is defined as static to allow you to use without an object reference.
Yes you can
you need to call the function from the controller like this
$data = ['YOUR ARRAY'];
$this->usersModel = new UsersModel();
$this->usersModel->insertData($data);
You can also do with static function
In Model
public static function insertData($data) {
In Controller
UsersModel::insertData($data);
Insert function
UsersModel::insert($data);

What's wrong with my Laravel 5.5 save() method?

I am using Laravel 5.5, I want to do basic form input where is only one field->"email". I am using Eloquent, model to interact with database for these subscriber inputs. When the controller method is called, this error follows:
FatalThrowableError (E_ERROR) Call to a member function save() on
string
The thing is I am using exactly the same solution for other form I've got in my application (contact form). That's the reason why I am pretty sure, that namespacing, models or other stuff I written well.
This is my code:
SubsController.php
class SubsController extends Controller
{
public function store(Request $request)
{
$subscriber = new Subscriber;
$subscriber=$request->input('email');
$subscriber->save();
return redirect()->to(route('homepage'));
}
}
Please check this line, you just assigned a string value to your $subscriber variable
$subscriber =$request->input('email');
The correct way is
public function store(Request $request) {
$subscriber = new Subscriber;
$subscriber->email =$request->input('email');
$subscriber->save();
return redirect()->to(route('homepage'));
}
Here is the solution :
$subscriber = new Subscriber;
$subscriber->email = $request->input('email');
$subscriber->save();
return redirect()->to(route('homepage'));
One more solution is
public function store() {
$data = request()->validate('email');
Subscriber::create($data);
return redirect()->route('homepage');
}

Laravel polymorphic relations: Passing model to controller

I want to use a single controller to save my comments for multiple models. So I created the CommentController, with the following store method:
public function store(Teacher $teacher, Request $request)
{
$input = $request->all();
$comment = new Comment();
$comment->user_id = Auth::user()->id;
$comment->body = $input['body'];
$teacher->comments()->save($comment);
return redirect()->back();
}
In my view, I have:
{!! Form::open([
'route' => ['teachers.comments.store', $teacher->id]
]) !!}
This is working. If I want to use the same CommentController to store the comments for a school, how should I modify the store method of the controller?
Adam's solution is great, but I would not hard-code the model's namespace that way. Instead, what I would do is make use of Laravel's Relation::morphMap(), you can check it out here: https://laravel.com/docs/5.6/eloquent-relationships#polymorphic-relations
That way, you will also make your database entries more readable. I recommend using a service provider to map the morphs.
Also, the Model base class has a getMorphClass() method, so instead of
$comment->commentable_type = 'App\\Models\\'.$model;
I would use
$comment->commentable_type = $model->getMorphClass();
That way you integrate Laravel's logic into your code.
Im not sure if this is the Laravel convension, but i have done the following:
Made a route:
Route::post('/Comment/{model}/{id}', [
// etc
]);
Then in the controller get the model and check against an array of allowed models, pass the id through and attach:
public function store(Request $request, $model, $id) {
$allowed = ['']; // list all models here
if(!in_array($model, $allowed) {
// return redirect back with error
}
$comment = new Comment();
$comment->user_id = $request->user()->id;
$comment->commentable_type = 'App\\Models\\'.$model;
$comment->commentable_id = $id;
$comment->body = $request->body;
$comment->save();
return redirect()->back();
}
Like I say, there is most likely a much better way to accomplish, but this is how I've done it. It keeps it short and sweet and checks if the model can take a comment.
I implemented this way if you want, according to me it's the one of the bests way to do that.
// Route::post('/comments/{model}/{id}', 'CommentController#store');
class CommentController extends Controller {
protected $model;
public function __construct()
{
$this->model = Relation::getMorphedModel(
request()->route()->parameter('model')
);
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
dd($this->model); // return 'App\Post' or null
}
}

Laravel 5.2 - creating a model from a variable

I am trying to access dynamically models so that I can get the count for each of them depending on which string I pass to the function.
This is what my function in the controller looks like:
public function numberOf(Request $request){
$modelName = $request['option'];
$model = new $modelName;
$data = $model->count();
return json_encode($data);
}
But when I pass a string, like in this case 'Article' I get an error:
Fatal error: Class 'Article' not found
Even though I am calling it in the controller:
use App\Article;
I had to add App to model name, so that my function looks like this now and everything works fine now:
$modelName = 'App\\'.$request['option'];
$model = new $modelName;
$data = $model->count();
return json_encode($data);

Categories