Save data into database in Laravel 5 - php

First
I wrote a migration script.
Second
I run the php artisan migrate to migrate the table into my database.
Database
Now, I have a subscribes table in my database.
It has 2 fields : id, and email.
Route
Route::post('/subscribe', array('as' =>'subscribe','uses'=>'AccountController#postSubscribe'));
Model
<?php namespace App;
use Illuminate\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Model;
class Subscribe extends Model {
protected $table = 'subscribes';
//Validation Rules and Validator Function
public static function validator($input){
$rules = array(
'email' =>'required|email'
);
return Validator::make($input,$rules);
}
}
Controller
<?php namespace App\Http\Controllers;
use Input, Validator, Auth, Redirect;
class AccountController extends Controller {
public function postSubscribe() {
$subscribe = new Subscribe; <-------- Line#46 (BUG HERE)
$subscribe->email = Input::get('email');
$subscribe->save();
dd("Hi");
return Redirect::to('/')
->with('success','You have been successfully subscribe to us.');
}
}
?>
Error
Questions
Why can't I do $subscribe = new Subscribe;?
What is the best practice to insert data into database using Laravel 5 ?
Update
Thanks to #Mark Baker.
It seems that I have an issue with my namespace.
This namspacing is a bit confusing to me right now.
Can someone please clarify or explain that a bit ?
Anything is appreciated.
Thanks in advance.

Here is a high level overview of how namespaces work in PHP to try and help you understand this and give you a solution to your problem.
<?php
// This is the namespace of this file, as Laravel 5 uses PSR-4 and the
// App namespace is mapped to the folder 'app' the folder structure is
// app/Http/Controllers
namespace App\Http\Controllers;
// Use statements. You can include classes you wish to use without having
// to reference them by namespace when you use them further on in this
// namespaces scope.
use App\Subscribe;
class MyController extends BaseController
{
public function postSubscribe()
{
// You can now use the Subscribe model without its namespace
// as you referenced it by its namespace in a use statement.
$subscribe = new Subscribe();
// If you want to use a class that is not referenced in a use
// statement then you must reference it by its full namespace.
$otherModel = new \App\Models\Other\Namespace\OtherModel();
// Note the prefixed \ to App. This denotes that PHP should get this
// class from the root namespace. If you leave this off, you will
// reference a namespace relative to the current namespace.
}
}

You can try this, Simply use it :
$subscribe = new App\Subscribe;

Use App\Subscribe;.
Then you can use $subscribe = new Subscribe; in your code.

Related

Laravel / Mongdb - DB::collection() is not working

I am following this Laravel/Mongodb package: https://github.com/jenssegers/. Here if you go to this section https://github.com/jenssegers/laravel-mongodb#basic-usage-2 you can see that they are using DB::collection() method and passed the collection name to that.
Now, in my controller, I am trying to do this:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Models\Import;
use App\Models\Projects;
use Jenssegers\Mongodb\Collection;
use Jenssegers\Mongodb\Query\Builder;
class ImportController extends Controller
{
public function get_all_products() {
// Predefined key
$predefined_keys = [ 'image_link', 'title', 'price', 'brand', 'link' ];
// Get all the products
//$get_products = Import::paginate(10);
$get_products = DB::collection('products_1')->get();
return response()->json($get_products, 200);
}
}
but I don't get any result. Can you tell me what I am missing here?
My goal is to set the collectioin name directly in this controller not in Model.
Update:.
Here is my Import Mode:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Jenssegers\Mongodb\Eloquent\Model;
class Import extends Model
{
protected $connection = 'mongodb';
protected $collection = 'products_46';
// protected $table = 'projects';
}
Something is wrong with how you have configured this project.
From the documentation that you linked:
When using MongoDB connections, Laravel will automatically provide you with the corresponding MongoDB objects.
Yet in the comments you report that DB::collection('products_1')->get(); results in:
message": "Method Illuminate\\Database\\MySqlConnection::collection does not exist."
This error message is referencing MySQL rather than MongoDB. It seems you are using MySQL for other portions of your application per this question.
In any case, I think the answer is to be sure to load the packages appropriately (and perhaps also to disambiguate between namespaces if DB is separately defined in Illuminate\Support\Facades and is in scope for this portion of the code).

Use Imported Classes From Parent Class In a PHP Trait Laravel 5.5

I'm currently working on a PHP trait thay will help me to reuse code in some class controllers that I have using Laravel framework.
I wanted to make the trait methods as dynamic as I could but when trying to access to a class that my parent class imported, I get a Class not found exception.
My class controller is as follows:
namespace App\Http\Controllers\Admin;
use App\Models\ {
Curso,
Leccion,
Diapositiva,
ImagenDiapositiva
};
use App\Traits\TestTrait;
class DiapositivasController extends Controller{
use TestTrait;
public function addRecord(Request $request){
$request->class_name = 'ImagenDiapositiva';
$this->addImage($request);
}
}
My Trait:
namespace App\Traits;
trait TestTrait{
public function addImage($request){
$class_name = $request->class_name;
$diapositiva = new $class_name;
//extra code
}
}
So my doubt is, do I have to include the model classes I want to use inside my Trait again or am I doing something else wrong?
if you use new with a variable class name, you have to use the fully qualified class name. I'm guessing new $class_name is the root cause of the issue here, since $class_name would have to be something like: 'App\Models\ImagenDiapositiva' or whatever the full namespace is. Just have to change the call $request->class_name = 'ImagenDiapositiva'; to reflect the full name of the class.

Using Laravel 5 Model

I have created a model using
php artisan make:model Sessions
which creates a model named Sessions in the App\ folder. My Model (Sessions) and the controller(School) calling the model are below
Model (Sessions):
<?php namespace App;
use Illuminate\Database\Eloquent\Model;
class Sessions extends Model {
//
protected $table = "sch_sessions";
protected $primaryKey = "session_id";
}
Controller (School)
<?php
namespace App\Http\Controllers;
use App;
class SchoolController extends Controller {
public function sessionManagement(){
$Sessions = Sessions::all();
}
}
I get the following error
FatalErrorException in SchoolController.php line 7: Class
'App\Http\Controllers\Session' not found
I've tried putting the model in a folder and "use"ing it but nada. I'm stumped as to why the error is referring to a controller in the first place. Can anyone see something I don't (can't) please?
add on the top
use App\Sessions;
or use it with prefix
\App\Sessions::all();
If user Ali Mohammed's answer doesn't clear it up for you, it looks to me like your error is happening elsewhere. App\Http\Controllers\Session note Session is not plural.
Are you attempting to use the Session class elsewhere in your controller? If so, make sure to prefix it so it's using the Session declared in the global namespace. You can do this with \Session.

Can't get user_id Laravel with Auth::user() just with \Auth::user()

sorry if it is a noob question, but I'm trying to learn laravel on laracast and can't solve this by my own.
there is a store function on my ArticlesController like this:
public function store(ArticleRequest $request)
{
$article = new Article($request->all());
Auth::user()->articles()->save($article);
return redirect('articles');
}
and it returns a blank page, making clear that is some error, but if I change to
\Auth::user()->articles()->save($article);
it works as expected, saving the article with the user_id field.
I tried import with use App\Http\Controllers\Auth\AuthController; but I think this is not the way.
*obs: Laravel 5.0
In modern PHP, if you see the following at the top of a file
namespace App\Foo\Bar;
it means all the code inside that file in part of the App\Foo\Bar namespace. If you try to use a namespaceless class inside this file
$object = new Auth;
PHP will assume you want to use the class. In other words, it's the same as saying
$object = \App\Foo\Bar\Auth;
When you say
\Auth
you're telling PHP "use the global, top level namespace class named Auth.
This is a perfectly valid use of PHP, by the way. However, if you don't like using the global \ -- you can import the \Auth class into your PHP file (sometimes referred to as a "module" in other languages") by using the use statement.
namespace App\Foo\Bar;
//pull in the global class `Auth`
use Auth;
//...
$foo = new Auth;

Yii 2 Namespace missing?

I have a namespace missing problem in Yii 2. I installed the advanced application. I am referencing a backend model from my frontend controller. Below is a code snippet of my backend model, frontend controller and error message.
Error
Unable to find 'backend\models\PaymentsMethod\TermsAndConditions' in file: C:\inetpub\wwwroot\jobmanager/backend/models/PaymentsMethod/TermsAndConditions.php. Namespace missing?
Backend Model
namespace app\models\PaymentsMethod;
use Yii;
class TermsAndConditions extends \yii\db\ActiveRecord
{
Frontend Model
public function actionCreate()
{
$model = new estimate();
$tnc = new \backend\models\PaymentsMethod\TermsAndConditions();
I have resolved my problem. I was trying to access a backend model class from a frontend controller. I resolved this by moving the backend model class to the common folder and from there I can reference it from both the backend and frontend.
Thanks
In your frontend, first include the namespace and then instantiate:
use app\models\PaymentsMethod\TermsAndConditions;
$tnc = new TermsAndConditions();
OR
As alfallouji said you can directly use:
$tnc = new \app\models\PaymentsMethod\TermsAndConditions();
If you are accessing from frontend then use frontend instead of app
i.e
namespace frontend\models\PaymentsMethod;
and if you are accessing from backend then use as below
namespace backend\models\PaymentsMethod;
You defined the model using this namespace app\models\PaymentsMethod and then you are trying to instantiate \backend\models\PaymentsMethod\TermsAndConditions.
You should be doing that in your frontend model :
$tnc = new \app\models\PaymentsMethod\TermsAndConditions();
Namespace declaration statement has to be the very first statement in the script
123456789101112
<?php
namespace app\controllers;
use yii\web\Controller;
use app\models\users;
class UserController extends Controller{
public function actionIndex()
{
echo "working on .....";
replace "backend" for "app" only models search
ex: app\models\PaymentsMethod;

Categories